C# 获得一个窗口&x27;s区

C# 获得一个窗口&x27;s区,c#,graphics,screen-capture,region,C#,Graphics,Screen Capture,Region,我正在尝试使用以下方法获取窗口的高度和宽度: [DllImport("User32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags); [DllImport("user32.dll", CharSet = CharSet.Au

我正在尝试使用以下方法获取窗口的高度和宽度:

    [DllImport("User32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr handle, out Rectangle rect);

    private void timer1_Tick(object sender, EventArgs e)
    {
        Rectangle bonds = new Rectangle();
        GetWindowRect(GetForegroundWindow(), out bonds);
        Bitmap bmp = new Bitmap(bonds.Width, bonds.Height);
        Graphics memoryGraphics = Graphics.FromImage(bmp);
        IntPtr dc = memoryGraphics.GetHdc();
        PrintWindow(GetForegroundWindow(), dc, 0x1);
        memoryGraphics.ReleaseHdc(dc);
        bmp.Save("C:\\Test.gif", ImageFormat.Gif);
    }
但是宽度和高度比真正的窗户要大

示例:我的窗口是100x150,bond.height像400,bonds.width像500。我得到一张大小为400x500的图片,它由图片角落的窗口组成(这是好的),其余的是黑色的,因为图片比窗口大得多(这是坏的)

注:我不在乎窗户是否无风,这对我有好处

所以有什么建议,或者更好的获取区域的方法吗?

您需要使用并转换坐标


GetWindowRect返回相对于屏幕左上角(0,0)的窗口区域。

您的屏幕缩放是否奇怪(仅限Vista/Windows7)相对于屏幕左上角的缩放是否正确。我将尝试您的解决方案。它说我返回相对于屏幕左上角的点,但我仍然需要高度/宽度,所以我需要将两者结合起来?@User是的,在GetWindowRect调用后使用ScreenToClient,然后像往常一样减去以获得宽度/高度。@User看这个示例: