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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With