[英]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.