Search code examples
c#.netwinformswinapiprocess

Why does .Net change the Process.MainWindowHandle?


I created a new Windows Forms App in Visual Studio and added the following code to it:

new Form1().Show();

By calling this code, the Process.MainWindowHandle of my process, reported by Process.GetProcessById(Environment.ProcessId).MainWindowHandle will be changed to the new Form.

But if I activate the first created form again, the MainWindowHandle will be reported with the initially created form. So, if I'm right, the Process.MainWindowHandle always reports the active form handle and not the initially created form.

I've also tried to use a ApplicationContext with defining its MainForm property, but this does not change anything.

How and I define a MainForm in .Net with C#, which handles will be reported by Process.MainWindowHandle always, independent if it's active or hidden?


Solution

  • Inspired by the comments to my question, I found this solution to get the handle of my MainForm:

    With this code, I will find a windows handle of a process, which answers to a user defined Windows message:

    IntPtr mainFormHandle = IntPtr.Zero;
    foreach (ProcessThread thread in Process.GetProcessById(processId).Threads)
        EnumThreadWindows(
            (uint)thread.Id,
            (hWnd, lParam) =>
            {
                if (SendMessage(hWnd, WM_USER, 0, 0) == TRUE)
                    mainFormHandle = hWnd;
                return TRUE;
            },
            0);
    

    ... if the MainForm was found, the mainFormHandle is set to it's handle.

    To use this code, my MainForm has to answer the sent Windows message:

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_USER)
            m.Result = TRUE;
        else
            base.WndProc(ref m);
    }