![](/img/trans.png)
[英]Why does C# compiler produce method call to call BaseClass method in IL
[英]Why does this C# method not produce the right screenshot?
我想將標題以- Scrivener
結尾的 window 的快照保存在 PNG 文件中。 為此,我編寫了以下方法(基於此答案):
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
private void button1_Click(object sender, EventArgs e)
{
Process[] processes = Process.GetProcesses();
Process scrivenerProcess = null;
foreach (Process curProcess in processes)
{
Console.WriteLine("Name: " + curProcess.ProcessName + ", title: " + curProcess.MainWindowTitle);
if (curProcess.MainWindowTitle.EndsWith("- Scrivener"))
{
scrivenerProcess = curProcess;
break;
}
}
if (scrivenerProcess == null)
{
Console.WriteLine("Scrivener not found");
return;
}
var rect = new RECT();
GetWindowRect(new HandleRef(this, scrivenerProcess.MainWindowHandle), out rect);
int width = rect.Right - rect.Left;
int height = rect.Bottom - rect.Top;
var bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bmp);
graphics.CopyFromScreen(rect.Left, rect.Top, 0, 0, new System.Drawing.Size(width, height), CopyPixelOperation.SourceCopy);
bmp.Save("C:\\usr\\dp\\ref\\marcomm\\2020_04_22_wordCounter\\2020-04-24-TestScreenshot.png", ImageFormat.Png);
Console.WriteLine("Heyo!");
}
這段代碼有幾個問題:
首先,如果我在調用該代碼時要捕獲的應用程序(Scrivener)不在前台,則生成的屏幕截圖為空。
其次,如果 Scrivener window 在前台,我得到父 window 的屏幕截圖(見下文)。
我如何需要更改我的代碼才能使其
一個。 即使 window 不在前台並且
灣。 僅捕獲字數 window (不是其父級)?
這是代碼。
這是你的問題:
scrivenerProcess.MainWindowHandle
從文檔中:
主window是當前有焦點的進程打開的window
在您的屏幕截圖中,您所追求的 window沒有焦點(它有一個帶有灰色文本的白色背景,表明它處於非活動狀態)。
不幸的是,要枚舉進程的其他 windows,您需要使用 P/Invoke,因為它們不會通過Process
class 公開。 使用EnumWindows
或EnumChildWindows
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.