Process.GetCurrentProcess().MainWindowHandle returns zero

Viewed 11418

I'm trying to get the window handle (HWND) of the main form of my C# application (the application has only 1 form).

Some solutions on the internet show that I can use:

Process.GetCurrentProcess().MainWindowHandle

to get the window handle of current process of my application. But this value is always zero, anything wrong?

3 Answers

MSDN says:

The main window is the window opened by the process that currently has the focus (the TopLevel form). You must use the Refresh method to refresh the Process object to get the current main window handle if it has changed.

and

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. This can be the case for processes that appear as icons in the notification area, at the far right of the taskbar.

See http://msdn.microsoft.com/en-us/library/system.diagnostics.process.mainwindowhandle(v=vs.110).aspx

In properties [F4] window 'Show in Taskbar' should be True

try using

System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
Related