Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

c# - Unexpected behaviour of Process.MainWindowHandle

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")+"
");
        }

    }

    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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@edg,

I guess it's an error in MSDN. You can clearly see in Relfector, that "Main window" check in .NET looks like:

private bool IsMainWindow(IntPtr handle)
{
    return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero)  
             && NativeMethods.IsWindowVisible(new HandleRef(this, handle)));
}

When .NET code enumerates windows, it's pretty obvious that first visible window (i.e. top level window) will match this criteria.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...