Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get A Window's Bounds By Its Handle

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.

like image 530
user779444 Avatar asked Jun 20 '11 17:06

user779444


1 Answers

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;
        }
like image 197
MK. Avatar answered Sep 26 '22 20:09

MK.