gpt4 book ai didi

c# - 事件窗口外边框截图

转载 作者:行者123 更新时间:2023-11-30 18:27:06 25 4
gpt4 key购买 nike

我最近找到了一个代码来制作事件窗口的屏幕截图。它确实有效,但是图像有点太大,有点超出当前窗口的边界。

这是我的程序截图: this is the screenshot taken with my program

这是用 alt+printscreen 截取的截图: This is the screenshot taken with alt+printscreen

这是我的课:

public static class Screenshotter
{
[DllImport("user32.dll")]
static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

[DllImport("user32.dll")]
private static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

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

public static void MakeScreenshot()
{
var foregroundWindowsHandle = GetForegroundWindow();
var rect = new RECT();

GetWindowRect(foregroundWindowsHandle, out rect);

Rectangle bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);

Bitmap bmp = new Bitmap(bounds.Width, bounds.Height);

using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}

bmp.Save("test.png", ImageFormat.Png);
}
}

我只希望它截取事件窗口的屏幕截图,而不是窗口外的一点点。我希望有人能帮助我:)

最佳答案

我遇到了您所描述的症状的问题。在我的例子中,这是由于窗口在系统中注册为“前景”和它实际完全显示在其他窗口前面的屏幕上的时刻之间的延迟。您可能观察到相同的情况。当您执行 g.CopyFromScreen(...) 时,您会从屏幕区域获取像素,该区域可能仍在从前一个前景窗口过渡到当前窗口。
在第一个保存的图像中,您可以看到我的图像捕获程序启动后 150 毫秒内截取的前景窗口(命令提示符)的屏幕截图:

Screenshot of "foreground" window in with 150 milliseconds delay

如您所见,它是前一个前景窗口像素 (Visual Studio) 和新像素的混合。

又花了 150 毫秒来完全更新屏幕: Screenshot of fully updated foreground window (300 ms delay)

因此,不是您的屏幕截图尺寸有误——而是新的前景窗口尚未“膨胀”到其最终边界。一个简单(且丑陋)的解决方案是:在调用 g.CopyFromScreen(...) 之前插入 Thread.Sleep(...) 以给系统足够的时间来完全替换屏幕上的像素。

关于c# - 事件窗口外边框截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27363272/

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