5

I am trying to find the window size of a new process that I am opening, but it is returning 0 for the height and width. Here is my code:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT 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
}

static void Main(string[] args)
{
    Process process = new Process();
    process.StartInfo.FileName = @"C:\Program Files (x86)\FirstClass\fcc32.exe";
    //C:\Program Files (x86)\FirstClass\fcc32.exe
    process.Start();

    Console.WriteLine(process.HandleCount);
    IntPtr hWnd = process.MainWindowHandle;

    RECT rect = new RECT();
    process.WaitForInputIdle();
    GetWindowRect(hWnd, ref rect);
    int width = rect.Right - rect.Left;
    int height = rect.Bottom - rect.Top;

    Console.WriteLine("Height: " + height + ", Width: " + width);
    Console.ReadLine();
}
nickb
  • 59,313
  • 13
  • 108
  • 143
asdfasdfadsf
  • 381
  • 3
  • 14
  • What is the return value of the call to `GetWindowRect()`? Is it true or false? – Jens Meinecke Jan 27 '16 at 01:10
  • 1
    If process.MainWindowHandle is not NULL then I would use Spy++ on your fcc32 application to see what the properties are of that window. It might be that your top level window is has a size of 0,0....and is acting as the parent of the actual visible windows that are created. Also try calling "Refresh"....http://stackoverflow.com/questions/16185217/c-sharp-process-mainwindowhandle-always-returns-intptr-zero – Colin Smith Jan 27 '16 at 01:14

2 Answers2

7

Thanks for the answers everybody, but the actual problem was that I was doing

IntPtr hWnd = process.MainWindowHandle;

before the process window had actually had a chance to open.

asdfasdfadsf
  • 381
  • 3
  • 14
-1

The signature is wrong it should be:

[DllImport("user32.dll", SetLastError=true)]
static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);

change calling code accordingly:

RECT rect;
process.WaitForInputIdle();
GetWindowRect(hWnd, out rect);
Jens Meinecke
  • 2,904
  • 17
  • 20