【问题标题】:Get A Window's Bounds By Its Handle通过句柄获取窗口的边界
【发布时间】:2011-06-20 17:43:31
【问题描述】:

我正在尝试获取当前活动窗口的高度和宽度。

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

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

Rectangle bonds = new Rectangle();
GetWindowRect(handle, bonds);
Bitmap bmp = new Bitmap(bonds.Width, bonds.Height);

此代码不起作用,因为我需要使用RECT,但我不知道如何使用。

【问题讨论】:

    标签: c# winapi graphics


    【解决方案1】:

    这样的事情google很容易回答(C#GetWindowRect);您还应该了解 pinvoke.net——从 C# 调用本机 API 的绝佳资源。

    http://www.pinvoke.net/default.aspx/user32/getwindowrect.html

    我想为了完整起见,我应该在这里复制答案:

            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);
    
            [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
            }
    
            Rectangle myRect = new Rectangle();
    
            private void button1_Click(object sender, System.EventArgs e)
            {
                RECT rct;
    
                if(!GetWindowRect(new HandleRef(this, this.Handle), out rct ))
                {
                    MessageBox.Show("ERROR");
                    return;
                }
                MessageBox.Show( rct.ToString() );
    
                myRect.X = rct.Left;
                myRect.Y = rct.Top;
                myRect.Width = rct.Right - rct.Left;
                myRect.Height = rct.Bottom - rct.Top;
            }
    

    【讨论】:

    • 创建一个新的 RECT 结构是多余的,System.Drawing.Rectangle 布局是一样的。
    • @pikzen:不一样。矩形有宽度和高度,矩形有右边和底部。
    • @pikzen 这就像说使用类型是一种矫枉过正,它只是字节。
    • @pikzen - 不,使用 Reflector 查看 Rectangle 的私有字段。它真正存储宽度和高度,而不是右下角。不同的写法不同的值。
    • 我认为宽度和高度计算不应该有+1。
    【解决方案2】:

    当然,该代码不起作用。它必须是这样的:GetWindowRect(handle, ref rect);。所以,编辑你的GetWindowRect 声明。而Rectangle 只是原生RECT 的包装。 RectangleRECT 具有左、上、右和下字段,矩形类更改为读取属性(LeftTopRightBottom)。 Width 不等于 right,Height 不等于 bottom。 Width 是从右到左,Height 是自下而上。当然,RECT 没有这些属性。它只是一个裸结构。

    创建RECT 太过分了。 Rectangle 在 .NET 中对于需要它的本机/非托管 API 来说已经足够了。你只需要以适当的方式传递它。

    【讨论】:

    • 我想直接对OP的帖子发表评论,但由于我不能,我就在这里做。 CharSet 和 ExactSpelling 不是必需的。 user32.dll 中只有一个 GetForegroundWindow 声明。没有 ANSI 和 unicode 版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2012-11-22
    • 2011-02-26
    • 1970-01-01
    相关资源
    最近更新 更多