views:

39

answers:

1

Instance A is trying to restore instance B's window, but I can't get the B's window handle. I think the problem is that the window is being minimized by B to the system tray using:

this.Visibility = Visibility.Hidden;

And A is trying to get B's window handle using:

Process process = Process.GetCurrentProcess();
Process.GetProcessesByName(process.ProcessName).First().MainWindowHandle;

Which is equal to IntPtr.Zero.

I also tried to get the window handle by class name using Spy++ but the class name has a per-instance GUID in the following format:

HwndWrapper[FileName.exe;;ad445199-cf93-48a4-bd24-2f97d54c8af8]
+1  A: 

That is because what you want basically doesn't exists, and the concept of MainWindowHandle is a gross misnomer that sneaked into the .Net Framework for everlasting confusion. From There can be more than one (or zero): Converting a process to a window:

"I have a thread ID. How do I get the corresponding window?"

You can use the EnumThreadWindows function to get all the windows on the thread.

"Yes, I know about EnumThreadWindows, but how do I get the window that I want?"

Well, you haven't said what you wanted yet.

"I want the window that corresponds to the thread."

But which one? How will you decide among all the windows?

"That's what I'm asking you!"

But you haven't yet described what you want.

"I want the window corresponding to the thread. Why won't you answer my question?"

Note that saying, "I am looking for the top-level unowned window" is a step forward, but it still doesn't uniquely identify a window. There can be multiple top-level unowned windows in a process. For example, Explorer typically has lots of top-level unowned windows. There's the desktop, the taskbar, your open folder windows, and property sheets. If you ask for "the" top-level unowned window of Explorer, which one do you want?

Perhaps people are getting the idea that there is a way to uniquely specify "the" window for a process because the System.Diagnostics.Process object has a property called MainWindowHandle. The documentation for that property doesn't do anything to dispel the notion, either. I have no idea how that property decides among multiple top-level unowned windows.

The topic is also elaborated in MSDN Q&A Get the Main Window:

Q How can I find the main window for a process? I'm writing a Spy-like tool and I need to get the main window (HWND) for a process so I can send it a message like WM_ACTIVATEAPP.

A Which main window do you mean?

Remus Rusanu