<p>I've been trying to understand <a href="http://msdn.microsoft.com/en-gb/library/system.diagnostics.process.mainwindowhandle.aspx" rel="nofollow noreferrer">Process.MainWindowHandle</a>.</p>

<p>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 <em>the first window associated with the process remains the main window</em>." (Emphasis added)</p>

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

<p>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.</p>

<p>Here's the interesting part of this test app...</p>

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

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

<p><img src="https://i.stack.imgur.com/r54iB.png" alt="MainWindowHandleMystery"></p>

<p>Perhaps I've misunderstood the documentation.  </p>

<p>Can anyone shed light?</p>

[{'answer_id': 48301, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': '<p>Actually Process.MainWindowHandle is a handle of top-most window, it\'s not really the "Main Window Handle"</p>\n'}, {'answer_id': 48318, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 5, 'selected': True, 'text': '<p>@edg,</p>\n\n<p>I guess it\'s an error in MSDN. You can clearly see in Relfector, that "Main window" check in .NET looks like:</p>\n\n<pre><code>private bool IsMainWindow(IntPtr handle)\n{\n    return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero)  \n             &amp;&amp; NativeMethods.IsWindowVisible(new HandleRef(this, handle)));\n}\n</code></pre>\n\n<p>When .NET code enumerates windows, it\'s pretty obvious that first visible window (i.e. top level window) will match this criteria.</p>\n'}]
['https://Stackoverflow.com/questions/48288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4200/']