酢ろぐ!

カレーが嫌いなスマートフォンアプリプログラマのブログ。

Windows Mobileでタイトルバー領域とソフトキー領域を含めずに画面イメージをキャプチャーする

タイトルバーとソフトキーを含めないアプリ描画部分の画面イメージをキャプチャーする方法です。

Windows Mobile(.NET Compact Frameworks)でタイトルバー領域とソフトキー領域を含めて画面イメージをキャプチャーする - 酢ろぐ!」のタイトルバーとソフトキーを含めない版のコードです。

以下にサンプルコードを示す。

|cs| public class Window2 { private const int SRCCOPY = 0xCC0020;

  [DllImport("coredll.dll")]
  private static extern int BitBlt(IntPtr hDestDC,
      int x, int y, int nWidth, int nHeight, IntPtr hSrcDC,
      int xSrc, int ySrc, int dwRop);

  [DllImport("coredll.dll")]
  private static extern IntPtr ReleaseDC(IntPtr hwnd, IntPtr hdc);

  [StructLayout(LayoutKind.Sequential)]
  private struct RECT
  {
      public int left;
      public int top;
      public int right;
      public int bottom;
  }

  [DllImport("coredll.dll")]
  private static extern IntPtr GetWindowDC(IntPtr hwnd);

  [DllImport("coredll.dll")]
  private static extern IntPtr GetForegroundWindow();

  [DllImport("coredll.dll")]
  private static extern int GetWindowRect(IntPtr hwnd,
      ref  RECT lpRect);

  public static Bitmap CaptureActiveWindow()
  {
      IntPtr hWnd = GetForegroundWindow();
      IntPtr winDC = GetWindowDC(hWnd);

      RECT rect = new RECT();
      GetWindowRect(hWnd, ref rect);

      Bitmap bmp = new Bitmap(rect.right - rect.left,
                              rect.bottom - rect.top);
      using (Graphics g = Graphics.FromImage(bmp))
      {
          IntPtr hDC = g.GetHdc();
          BitBlt(hDC, 0, 0, bmp.Width, bmp.Height, winDC, 0, 0, SRCCOPY);
          g.ReleaseHdc(hDC);
      }
      ReleaseDC(hWnd, winDC);

      return bmp;
  }

} ||<