通过它的句柄获得一个窗口的界限

我试图获得当前活动窗口的高度和宽度。

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

当然,该代码不起作用。 它必须是这样的: GetWindowRect(handle, ref rect); 。 因此,编辑GetWindowRect声明。 而Rectangle只是原生RECT的包装器。 RectangleRECT有left,top,right和bottom字段,Rectangle类更改为read-properties( LeftTopRightBottom )。 Width不等于右边, Height不等于底部。 Width为左右, Height为左下角。 当然, RECT没有这些属性。 它只是一个简单的结构。

创建RECT是一种过度杀伤力。 .NET中的Rectangle足以满足需要它的本机/非托管API。 你只需要以适当的方式传递它。