【问题标题】:Getting A Window's Region获取窗口的区域
【发布时间】:2011-06-20 22:44:02
【问题描述】:

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

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

但是bonds.width 和height 比真实的窗口要多。

示例:我的窗口为 100x150,bond.height 为 400,bond.width 为 500。我得到一张大小为 400x500 的图片,其中包含图片角落的窗口(这很好)和其余的都是黑色的,因为图片比窗口大得多(这很糟糕)

注意:我不在乎窗户是无气的,这对我有好处。

那么有什么建议,或者是获得地区的更好方法吗?

【问题讨论】:

  • 你的屏幕缩放是否奇怪(仅限 Vista/Windows7)

标签: c# graphics screen-capture region


【解决方案1】:

您需要使用ScreenToClient 并转换坐标。

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

【讨论】:

  • 哦,相对于屏幕的左上角,现在说得通了。我会试试你的解决方案。
  • 它说我返回相对于屏幕左上角的点,但我仍然需要高度/宽度,所以我需要将两者结合起来?
  • @User 是的,在 GetWindowRect 调用之后使用 ScreenToClient,然后像往常一样减去以获得宽度/高度。
  • @User 看这个例子:improve.dk/archive/2007/04/09/…
猜你喜欢
  • 2018-05-14
  • 2016-11-11
  • 2011-08-21
  • 1970-01-01
  • 2018-07-05
  • 2012-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多