Reputation: 19214
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;
}
}
Upvotes: 2
Views: 6440
Reputation: 9940
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.
Upvotes: 3
Reputation: 3731
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.
Upvotes: 1
Reputation: 2514
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.
Upvotes: 3