asdfasdfadsf
asdfasdfadsf

Reputation: 391

GetWindowRect returning 0

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

Upvotes: 5

Views: 2993

Answers (2)

asdfasdfadsf
asdfasdfadsf

Reputation: 391

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.

Upvotes: 7

Jens Meinecke
Jens Meinecke

Reputation: 2940

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

Upvotes: -1

Related Questions