views:

1229

answers:

3

How to get main window handle from process id?

I want to bring this window to the front.

It works well in "Process Explorer".

+2  A: 

I think you're looking for Process.MainWindowHandle

Edit: If you're not using .Net/C++, then this is what you're looking for.

hometoast
it's tagged C++ and winapi so he can't use MainWindowHandle, the link looks like what he needs
Idan K
Besides, the .Net property has just arbitrarily chosen a definition for "main window." It doesn't have any special privilege to discover a process's main window because the OS has *no such concept*. See http://stackoverflow.com/questions/48288/unexpected-behaviour-of-process-mainwindowhandle for further discussion of what that property really means.
Rob Kennedy
+5  A: 

I don't believe Windows (as opposed to .NET) provides a direct way to get that.

The only way I know of is to enumerate all the top level windows with EnumWindows() and then find what process each belongs to GetWindowThreadProcessID(). This sounds indirect and inefficient, but it's not as bad as you might expect -- in a typical case, you might have a dozen top level windows to walk through...

Jerry Coffin
How do I know that the main window?
Alexey Malistov
+1. You described exactly what the msdn article link suggested. But in about 1000 words less.
hometoast
@Alexey:From MSDN: "The EnumWindows function does not enumerate child windows."
Jerry Coffin
@hometoast:Experience breeds brevity. I published the method four years before that article.
Jerry Coffin
+3  A: 

There's the possibility of a mis-understanding here. The WinForms framework in .Net automatically designates the first window created (e.g., Application.Run(new SomeForm())) as the MainWindow. The win32 API, however, doesn't recognize the idea of a "main window" per process. The message loop is entirely capable of handling as many "main" windows as system and process resources will let you create. So, your process doesn't have a "main window". The best you can do in the general case is use EnumWindows() to get all the non-child windows active on a given process and try to use some heuristics to figure out which one is the one you want. Luckily, most processes are only likely to have a single "main" window running most of the time, so you should get good results in most cases.

Dathan