不是确切的解决方案,而是一些指向正确方向的提示。以下代码截取具有指定矩形的给定对话框的屏幕截图。您可以修改它以从客户区的屏幕截图中提取文本框(没有标题栏的对话框,...)
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWINFO
{
public UInt32 cbSize;
public RECT rcWindow;
public RECT rcClient;
public UInt32 dwStyle;
public UInt32 dwExStyle;
public UInt32 dwWindowStatus;
public UInt32 cxWindowBorders;
public UInt32 cyWindowBorders;
public UInt16 atomWindowType;
public UInt16 wCreatorVersion;
}
通过 P/I 的一点原生魔法:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetWindowInfo(IntPtr hwnd, ref WINDOWINFO windowInfo);
[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
对话框截图方法。使用任何 Windows 窗体的 Handle-property 获取 hwnd。
protected Bitmap Capture(IntPtr hwnd, Rectangle rect)
{
WINDOWINFO winInf = new WINDOWINFO();
winInf.cbSize = (uint)Marshal.SizeOf(winInf);
bool succ = PINativeOperator.GetWindowInfo(hwnd, ref winInf);
if (!succ)
return null;
int width = winInf.rcClient.right - winInf.rcClient.left;
int height = winInf.rcClient.bottom - winInf.rcClient.top;
if (width == 0 || height == 0)
return null;
Graphics g = Graphics.FromHwnd(hwnd);
IntPtr hdc = g.GetHdc();
if(rect == Rectangle.Empty) {
rect = new Rectangle(0, 0, width, height);
}
Bitmap bmp = new Bitmap(rect.Width, rect.Height);
Graphics bmpG = Graphics.FromImage(bmp);
PINativeOperator.BitBlt(bmpG.GetHdc(), 0, 0, rect.Width, rect.Height, hdc, rect.X, rect.Y, TernaryRasterOperations.SRCCOPY);
bmpG.ReleaseHdc();
return bmp;
}