我有一个C#控制台应用程序,可以多次截取MS Word文档的屏幕截图。它工作得很好,但是当我将此应用程序放在远程Windows XP机器上时,在我使用远程桌面时(即我的远程桌面可见),它运行良好,但是如果我运行我的应用程序并离开远程桌面(最小化它,甚至不需要注销),它所拍摄的截图都是空白的!
屏幕截图应用程序由一个以SYSTEM用户身份运行的服务运行。
如何使GUI在没有用户连接时仍然保持活动状态?
这是我使用的代码:
public Image CaptureWindow(IntPtr handle)
{
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle, ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
// using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY);
// restore selection
GDI32.SelectObject(hdcDest, hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle, hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
}
更新
我目前正在使用PrintWindow,它是唯一能够最接近地捕获窗口框架(即最小化、最大化和关闭按钮)的方法,但内部是黑色的。
尽管它还没有完全成功,但已经向我证明了在应用程序不可见的情况下,可以从窗口句柄创建图像。