Get A Window's Bounds By Its Handle

后端 未结 2 1472
名媛妹妹
名媛妹妹 2020-12-06 05:38

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

[DllImport(\"user32.dll\", CharSet = CharSet.Auto, ExactSpelling = true)]
public st         


        
相关标签:
2条回答
  • 2020-12-06 05:56

    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.

    0 讨论(0)
  • 2020-12-06 06:01

    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;
                myRect.Height = rct.Bottom - rct.Top;
            }
    
    0 讨论(0)
提交回复
热议问题