繁体   English   中英

如何获取 C# 中特定 window 的屏幕截图?

[英]How can I get screenshot of a specific window in C#?

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

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);

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

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

[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);
}

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

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM