2011-04-18 83 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

相關問題