Unexpected behaviour of Process.MainWindowHandle

Posted by Ed Guiness on Stack Overflow See other posts from Stack Overflow or by Ed Guiness
Published on 2008-09-07T10:14:23Z Indexed on 2010/12/23 7:54 UTC
Read the original article Hit count: 195

Filed under:
|
|

I've been trying to understand Process.MainWindowHandle.

According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but the first window associated with the process remains the main window." (Emphasis added)

But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above.

To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms.

Here's the interesting part of this test app...

    IntPtr oldHWnd = IntPtr.Zero;

    void GetMainwindowHandle()
    {
        Process[] processes = Process.GetProcessesByName("DEVENV");

        if (processes.Length!=1)
            return;

        IntPtr newHWnd = processes[0].MainWindowHandle;

        if (newHWnd != oldHWnd)
        {
            oldHWnd = newHWnd;
            textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n");
        }

    }

    private void timer1Tick(object sender, EventArgs e)
    {
        GetMainwindowHandle();
    }

You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS.

MainWindowHandleMystery

Perhaps I've misunderstood the documentation.

Can anyone shed light?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET