Sometimes you need to capture active window, there is a solution. Following code shows you, how to capture it. I will make two classes, which imports external code from user32.dll and gdi32.dll. (Windows API , etc..)
Attention: It captures active window. So if you want to capture any other window, it will not work. For example: if you call this code from click to Notify icon, it captures Notify bar (exactly it captures blank screen.).
User32Helper
public class User32Helper
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern int GetActiveWindow();
[DllImport("user32.dll")]
public static extern int GetTopWindow(int hWnd);
[DllImport("user32.dll")]
public static extern int GetNextWindow(IntPtr hWnd, int wCmd);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("User32.dll")]
public static extern int GetDesktopWindow();
[DllImport("User32.dll")]
public static extern int GetWindowDC(int hWnd);
[DllImport("User32.dll")]
public static extern int ReleaseDC(int hWnd, int hDC);
//keyboard
[DllImport("user32")]
public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, intdwExtraInfo);
public const byte VK_MENU = 0×12;
public const byte VK_TAB = 0×09;
public const int KEYEVENTF_EXTENDEDKEY = 0×01;
public const int KEYEVENTF_KEYUP = 0×02;
public const int GW_HWNDPREV = 0×03;
}
GDI32Helper
class GDI32Helper
{
[DllImport("GDI32.dll")]
public static extern bool BitBlt(int hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, int hdcSrc, int nXSrc, int nYSrc, int dwRop);
[DllImport("GDI32.dll")]
public static extern int CreateCompatibleBitmap(int hdc, int nWidth, int nHeight);
[DllImport("GDI32.dll")]
public static extern int CreateCompatibleDC(int hdc);
[DllImport("GDI32.dll")]
public static extern bool DeleteDC(int hdc);
[DllImport("GDI32.dll")]
public static extern bool DeleteObject(int hObject);
[DllImport("GDI32.dll")]
public static extern int GetDeviceCaps(int hdc, int nIndex);
[DllImport("GDI32.dll")]
public static extern int SelectObject(int hdc, int hgdiobj);
}
Capturing active window
/// <summary>
/// Captures the active window.
/// </summary>
/// <returns></returns>
public static Bitmap CaptureActiveWindow()
{
User32Proxy.RECT rect;
int desktop = (int)User32Helper.GetForegroundWindow();
int hdcSrc = User32Helper.GetWindowDC(desktop);
int hdcDest = GDI32Helper.CreateCompatibleDC(hdcSrc);
User32Proxy.GetWindowRect(new IntPtr(desktop), out rect);
int hBitmap = GDI32Helper.CreateCompatibleBitmap(hdcSrc, rect.Right – rect.Left, rect.Bottom – rect.Top);
GDI32Helper.BitBlt(hdcDest, 0, 0, rect.Right – rect.Left, rect.Bottom – rect.Top, hdcSrc, 0, 0, 0×00CC0020);
return Image.FromHbitmap(new IntPtr(hBitmap));
}
References
References