首页 > 解决方案 > 如何在 C# 中获取特定窗口的屏幕截图?

问题描述

我使用 C# 中的 Graphics 类编写了一个截取屏幕截图的代码。编码-

Bitmap bitmapScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Width, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics graphicsScreenshot = Graphics.FromImage(bitmapScreenshot);
graphicsScreenshot.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);

虽然我找不到对任何打开的应用程序/窗口执行相同操作的方法,但是有没有办法使用 Graphics 类来做到这一点,如果不在 Graphics 类中,我该怎么做?任何帮助表示赞赏。

标签: c#graphicsbitmapwindowscreenshot

解决方案


您需要将要截屏的目标应用程序窗口带到前台,如下所示:

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(String lpClassName, String lpWindowName);

[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

public static void bringToFront(string title) {
    // Get a handle to the Calculator application.
    IntPtr handle = FindWindow(null, title);

    // Verify that Calculator is a running process.
    if (handle == IntPtr.Zero) {
        return;
    }

    // Make Calculator the foreground application
    SetForegroundWindow(handle);
}

一旦窗口位于前台,您可以截屏,这样您的代码将如下所示:

bringToFront("<Your target app window name>");
Bitmap bitmapScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Width, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics graphicsScreenshot = Graphics.FromImage(bitmapScreenshot);
graphicsScreenshot.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size);

推荐阅读