Why am I getting height and width 0?

Why am I getting height and width 0 using below:

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(); } 

Here is my definition of GetWindowRect:

  [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect); 

This is my definition for 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 } 

Thanks to everyone for any help.

+6
source share
3 answers

You pass the process handle to the GetWindowRect function, which expects a window handle. Naturally, this fails. You must send Notepad.MainWindowHandle .

+9
source

You may be asking for size before the notebook is fully started. Try the following:

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

I like to use pinvoke.net to test the health of all my PInvokes. GetWindowRect is well described in: http://pinvoke.net/default.aspx/user32/GetWindowRect.html

+1
source

Source: https://habr.com/ru/post/886160/


All Articles