2011-04-18 84 views
6

为什么我得到的0 HEIGH和宽度与下方:为什么我的高度和宽度都是0?

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 
    } 

谢谢大家的帮助。

+1

你是如何定义RECT的? – 2011-04-18 15:50:43

+2

我怀疑这是一场比赛 - 尝试在Start()行后加入几秒钟的睡眠时间让记事本启动并运行。不知道如何等待这个编程。 – Rup 2011-04-18 15:51:49

+0

另外,GetWindowRect返回的值是什么? – 2011-04-18 15:52:02

回答

9

你传入进程句柄的功能,GetWindowRect,期望一个窗口句柄。自然,这失败了。您应该发送Notepad.MainWindowHandle

+0

该死!你是对的,那是有效的。我以为MainWindowHandle会给我的cmd窗口,但它实际上是产生的记事本窗口?这与JSBangs的答案结合使用。 – Kay 2011-04-18 15:58:41

+3

@Kay进程句柄与窗口句柄完全不同。这只是在.net中,随着你的P/Invoke,你会失去安全性。在普通的win32代码中,当尝试混合进程句柄和窗口句柄时,你会遇到编译器错误。 – 2011-04-18 16:02:59

+0

谢谢你的解释,我一直在搅拌这两个! – Kay 2011-04-18 16:17:48

1

我喜欢用pinvoke.net来理智地检查我所有的PInvokes。 GetWindowRect详细描述如下:http://pinvoke.net/default.aspx/user32/GetWindowRect.html

+0

这就是我实际使用,我仍然无法得到它的工作。哦,亲爱的,我是一个完全的新手! – Kay 2011-04-18 15:53:05

+0

您是否从GetWindowRect返回true?如果没有,你有一个错误:http://msdn.microsoft.com/en-us/library/ms633519(v=vs.85).aspx – mcw0933 2011-04-18 15:58:29

5

在记事本完全启动之前,您可能正在查询大小。试试这个:

notePad.Start(); 
    notePad.WaitForInputIdle(); // Waits for notepad to finish startup 
    IntPtr handle = notePad.Handle; 
+0

我尝试过,但不幸的是没有造成差异。但它与Davids的结合起作用。 – Kay 2011-04-18 15:59:07

相关问题