我正在尝试捕获具有活动光标的当前窗口的屏幕截图。但如果是应用程序窗口,结果总是缺少标题栏:
private void CaptureActiveWindow()
{
IntPtr activeWindowHandle = GetForegroundWindow();
// Get the client area of the foreground window
GetClientRect(activeWindowHandle, out Rectangle rect);
Point topLeft = new Point(rect.Left, rect.Top);
// Convert the client area's top-left corner to screen coordinates
ClientToScreen(activeWindowHandle, out topLeft);
// Create a rectangle in screen coordinates that corresponds to the window's client area
Rectangle bounds = new Rectangle(topLeft.X, topLeft.Y, rect.Width, rect.Height);
// Capture the specified screen area
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size);
}
SaveImage(bitmap);
}
}
GetClientRect函数返回指定窗口的客户区域的客户坐标,根据定义,它不包括标题栏(以及边框和任何菜单)。要包含标题栏,请调用 GetWindowRect 函数。这需要对您的代码进行多次调整:
Rectangle。 (RECT 具有“右”和“下”字段,而“矩形”具有“宽度”和“高度”字段。)
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public Point Location => new Point(Left, Top);
public int Width => Right - Left;
public int Height => Bottom - Top;
public Size Size => new Size(Width, Height);
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
IntPtr activeWindowHandle = GetForegroundWindow();
GetWindowRect(activeWindowHandle, out RECT rect);
// Capture the specified screen area
using (Bitmap bitmap = new Bitmap(rect.Width, rect.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(rect.Location, Point.Empty, rect.Size);
}
SaveImage(bitmap);
}
dpiAware
设置:
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>