Get A Window's Bounds By Its Handle

2019-01-15 00:25发布

问题:

I am trying to get the height and the width of the current active window.

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

This code doesn't work because I need to use RECT and I don't know how.

回答1:

Things like this are easily answered by google (C# GetWindowRect); you should also know about pinvoke.net -- great resource for calling native APIs from C#.

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

I guess for completeness I should copy the answer here:

        [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 + 1;
            myRect.Height = rct.Bottom - rct.Top + 1;
        }


回答2:

Of course that code will not work. It has to be this way: GetWindowRect(handle, ref rect);. So, edit your GetWindowRect declaration. And Rectangle is just a wrapper of the native RECT. Rectangle and RECT has left, top, right and bottom fields that the Rectangle class changed to read-properties (Left, Top, Right, Bottom). Width is not equivalent to right and Height is not equivalent to bottom. Width is right-left and Height is bottom-top. Of course, RECT don't have these sort of properties. It's just a bare struct.

Creating RECT is an overkill. Rectangle is enough in .NET for native/unmanaged API that need it. You just have to pass it in the appropriate way.