gpt4 book ai didi

c# - 为什么这个 C# 方法不能生成正确的屏幕截图?

转载 作者:行者123 更新时间:2023-12-03 20:07:25 25 4
gpt4 key购买 nike

我想保存标题以 - Scrivener 结尾的窗口的快照在 PNG 文件中。为此,我写了以下内容 method (基于 this 答案):

        [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 窗口在前台,我会得到父窗口的屏幕截图(见下文)。

Screenshot of parent and child window

我需要如何更改我的代码才能使其

一种。即使窗口不在前景中也能工作

湾只捕获字数窗口(不是它的父窗口)?

Here是代码。

最佳答案

这是你的问题:

scrivenerProcess.MainWindowHandle

From the documentation :

The main window is the window opened by the process that currently has the focus



在您的屏幕截图中,您所在的窗口是 不是 有焦点(它有一个带有灰色文本的白色背景,表示它处于非事件状态)。

不幸的是,要枚举进程的其他窗口,您需要使用 P/Invoke,因为它们不会通过 Process 公开。类(class)。 Use EnumWindows or EnumChildWindows .

关于c# - 为什么这个 C# 方法不能生成正确的屏幕截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61406301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com