2

Why process.MainWindowHandle is zero in code below?

Process me = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(me.ProcessName))
                    {
                        if (process.Id != me.Id)
                        {
                            MessageBox.Show(string.Format("{0}", process.MainWindowHandle));
                            ShowWindow(process.MainWindowHandle, 5);
                            ShowWindow(process.MainWindowHandle,3);
                            SetForegroundWindow(process.MainWindowHandle);
                            break;
                        }
                    }
AVEbrahimi
  • 17,993
  • 23
  • 107
  • 210
  • Are you sure your process has a window associated with it? It might not. The actual window might be a process that is spawned off on its own right. – ouflak Mar 13 '14 at 08:43
  • 1
    The hidden window is actually another instance of this very process which is just hidden by ShowWindow. – AVEbrahimi Mar 13 '14 at 08:45

3 Answers3

3

That your window is hidden is a critically important detail.

From the MSDN article on the Process.MainWindowHandle Property:

A process has a main window associated with it only if the process has a graphical interface. If the associated process does not have a main window, the MainWindowHandle value is zero. The value is also zero for processes that have been hidden, that is, processes that are not visible in the taskbar.

ouflak
  • 2,458
  • 10
  • 44
  • 49
  • Thanks. So what should I do? – AVEbrahimi Mar 13 '14 at 12:44
  • I suppose you briefly could have the window be visible on the taskbar, and be checking with a timer on a short interval, for that window handle. Once you've got it, then hide your process as usual. That window handle will remain constant for as long as your process is running (http://stackoverflow.com/questions/6772634/can-a-window-handle-in-net-change-its-value). Even though MainWindowHandle is returning zero, as long as that window exists, you can access it via other means and send it messages. It seems though, that this might not be as certain if you are using a Form. Then... – ouflak Mar 13 '14 at 13:26
  • ... you may have to 'recreate' the handle to ensure you are accessing the same window. – ouflak Mar 13 '14 at 13:26
3

The Process.MainWindowHandle property uses heuristics to determine what the main window is, but this doesn't always work. Try using EnumWindows. I wrote a tutorial on how to use this.

David Klempfner
  • 8,700
  • 20
  • 73
  • 153
1

One thing to add to already excellent answers here:

If the app you're opening has a GUI but still doesn't show up in the taskbar, it's MainWindowHandle can't be found.

For eg: If you have access to the Winform app's code, go to the properties of the form and make sure this is True in the Icon section:

Mine was set to False and I had to learn this the hard way.

Ash K
  • 1,802
  • 17
  • 44