c# - 如何在 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 类中,我该怎么做?任何帮助表示赞赏。
解决方案
您需要将要截屏的目标应用程序窗口带到前台,如下所示:
[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);
推荐阅读
- android - 将对象的数组列表发送到下一个活动 Kotlin
- r - 用 jsonlite 在 R 中构造 json - 括号太多
- python-2.7 - 访问距离矩阵中的特定成对距离(scipy / numpy)
- ios - 在 Swift 中处理 MVVM 中子视图中的事件
- swift - 在 Swift 中包装一个值和将值显式声明为类型之间的区别
- java - 如何在整数数组、映射、哈希集等中找到给出相同结果的第一个和最后一个值?
- javafx - 无法在 Scene Builder / IntelJ 中打开文件
- curl - curl 获取请求响应不正确
- proxy - http_proxy 和 https_proxy 的区别
- javascript - 如何在浏览器中创建一个新的顶级环境?