捕获活动窗口(包括标题栏)的屏幕截图

问题描述 投票:0回答:1

我正在尝试捕获具有活动光标的当前窗口的屏幕截图。但如果是应用程序窗口,结果总是缺少标题栏:

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);
    }
}
c# winapi
1个回答
0
投票

GetClientRect函数返回指定窗口的客户区域的客户坐标,根据定义,它不包括标题栏(以及边框和任何菜单)。要包含标题栏,请调用 GetWindowRect 函数。这需要对您的代码进行多次调整:

  1. 声明一个 RECT 类型,并在 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);
    
    
  2. GetWindowRect 返回屏幕坐标,因此删除 ClientToScreen 调用,只需将各种 RECT 值直接传递给 CopyFromScreen 即可:

    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); }
    
    
  3. GetWindowRect 函数针对 DPI 进行了虚拟化。为了确保这不会导致任何问题,请将应用程序清单文件 (App.manifest) 添加到您的项目中,并选择加入

    dpiAware

     设置:

    <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
    
    
© www.soinside.com 2019 - 2024. All rights reserved.