您可以通过在桌面窗口的 hWnd 上调用 PrintWindow Win32 API 函数来获取屏幕截图。我在 Windows 7 和 Windows 8.1 上尝试过此操作,即使在全屏运行另一个应用程序(VLC Player)时它也能正常工作,因此它也有可能适用于游戏。这只会为您提供没有任务栏的桌面图像,但其他可见的正在运行的应用程序不会显示在其上。如果您也需要这些,那么您还需要获取它们的 HWND(例如,通过枚举所有正在运行的进程并获取它们的窗口句柄),然后使用相同的方法。
using System;
using System.Drawing; // add reference to the System.Drawing.dll
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
namespace DesktopScreenshot
{
class Program
{
static void Main(string[] args)
{
// get the desktop window handle without the task bar
// if you only use GetDesktopWindow() as the handle then you get and empty image
IntPtr desktopHwnd = FindWindowEx(GetDesktopWindow(), IntPtr.Zero, "Progman", "Program Manager");
// get the desktop dimensions
// if you don't get the correct values then set it manually
var rect = new Rectangle();
GetWindowRect(desktopHwnd, ref rect);
// saving the screenshot to a bitmap
var bmp = new Bitmap(rect.Width, rect.Height);
Graphics memoryGraphics = Graphics.FromImage(bmp);
IntPtr dc = memoryGraphics.GetHdc();
PrintWindow(desktopHwnd, dc, 0);
memoryGraphics.ReleaseHdc(dc);
// and now you can use it as you like
// let's just save it to the desktop folder as a png file
string desktopDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string screenshotPath = Path.Combine(desktopDir, "desktop.png");
bmp.Save(screenshotPath, ImageFormat.Png);
}
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PrintWindow(IntPtr hwnd, IntPtr hdc, uint nFlags);
[DllImport("user32.dll")]
static extern bool GetWindowRect(IntPtr handle, ref Rectangle rect);
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle);
}
}