C# 获得一个窗口&x27;它受它的控制
我正在尝试获取当前活动窗口的高度和宽度C# 获得一个窗口&x27;它受它的控制,c#,winapi,graphics,C#,Winapi,Graphics,我正在尝试获取当前活动窗口的高度和宽度 [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); Rectangl
[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的绝佳资源
我想为了完整起见,我应该把答案复制到这里:
[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;
}
当然,这些代码不会起作用。它必须是这样的:
GetWindowRect(handle,ref-rect)代码>。因此,编辑您的GetWindowRect
声明。而Rectangle
只是原生RECT
的包装Rectangle
和RECT
具有左、上、右和下字段,矩形类将这些字段更改为读取属性(left
,top
,right
,bottom
)<代码>宽度
不等同于右侧,高度
不等同于底部<代码>宽度为左右,高度
为上下。当然,RECT
没有这些属性。它只是一个简单的结构
创建
RECT
是一种过分的做法<代码>矩形在.NET中对于需要它的本机/非托管API来说已经足够了。您只需以适当的方式传递它。创建新的RECT结构太过繁琐,System.Drawing.Rectangle布局是相同的。@pikzen:它不一样。矩形有宽度和高度,矩形有右和下。@pikzen这就像说使用类型是一种过度使用,它只是字节。@pikzen-不,使用Reflector查看矩形的私有字段。它真正存储的是宽度和高度,而不是右侧和底部。不同的措辞和不同的值。我认为宽度和高度的计算不应该有+1。我想直接评论OP的帖子,但因为我不能,我就在这里做。字符集和精确拼写是不必要的。user32.dll中只有一个getForeGroundIndow声明。没有ANSI和unicode版本。