C# 为什么我的高度和宽度为0?
为什么我得到的高度和宽度为0,如下所示:C# 为什么我的高度和宽度为0?,c#,.net,winapi,C#,.net,Winapi,为什么我得到的高度和宽度为0,如下所示: static void Main(string[] args) { Process notePad = new Process(); notePad.StartInfo.FileName = "notepad.exe"; notePad.Start(); IntPtr handle = notePad.Handle; RECT windowRect = ne
static void Main(string[] args)
{
Process notePad = new Process();
notePad.StartInfo.FileName = "notepad.exe";
notePad.Start();
IntPtr handle = notePad.Handle;
RECT windowRect = new RECT();
GetWindowRect(handle, ref windowRect);
int width = windowRect.Right - windowRect.Left;
int height = windowRect.Bottom - windowRect.Top;
Console.WriteLine("Height: " + height + ", Width: " + width);
Console.ReadLine();
}
下面是我对GetWindowRect的定义:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
这是我对RECT的定义:
[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
}
谢谢大家的帮助。我喜欢使用pinvoke.net来检查我所有的pinvoke。GetWindowRect的详细描述如下:您可能在记事本完全启动之前查询大小。试试这个:
notePad.Start();
notePad.WaitForInputIdle(); // Waits for notepad to finish startup
IntPtr handle = notePad.Handle;
您正在将一个进程句柄传递给一个函数,
GetWindowRect
,该函数需要一个窗口句柄。当然,这是失败的。您应该改为发送Notepad.MainWindowHandle
。您是如何定义RECT的?我怀疑这是一场竞赛-尝试在Start()行之后添加几秒钟睡眠,让Notepad启动并运行。不知道如何以编程方式等待。另外,GetWindowRect返回的值是多少?@James-我已经更新了这个问题。@Kay直接从MSDN获得:“如果函数失败,返回值为零。若要获取扩展的错误信息,请调用GetLastError
”。这是我实际使用的,但我仍然无法让它工作。哦,天哪,我是个十足的傻瓜!从GetWindowRect返回的值是否为真?如果没有,你就错了:该死!你说得对,这很有效。我原以为MainWindowHandle会给我一个cmd窗口,但它实际上是生成的记事本窗口?这与JSBangs answer一起工作。@Kay进程句柄与窗口句柄完全不同。只是在.net中,使用P/Invoke,您会失去类型安全性。在普通的win32代码中,当尝试混合进程句柄和窗口句柄时,您可能会遇到编译器错误。我尝试过,但不幸的是,这并没有带来什么不同。但它与戴维斯的答案相结合起了作用。