How to find window handle from exe file's name

123iamking picture 123iamking · Dec 23, 2016 · Viewed 11.3k times · Source

Imagine I have Firefox and I open Firefox Start Page, then I should have a Window with the title: "Mozilla Firefox Start Page - Mozilla Firefox".

I can find window handle with the code below

HWND hwnd = ::FindWindow(0, _T("Mozilla Firefox Start Page - Mozilla Firefox"));

But what I want is find window handle from the window's exe file's name like this

HWND hwnd = FindWindowFromExe(_T("firefox.exe"));//How to make this function?

Does windows Api has a function like FindWindowFromExe()? If it doesn't, what is the best way to Find window from its exe?

Thanks for reading :)

Answer

Remy Lebeau picture Remy Lebeau · Dec 23, 2016

There is no single API function to find a window by its owning process's file name. You will have to search for it manually.

You can use EnumWindows() to enumerate all top-level windows, or use FindWindow()/FindWindowEx() to find/enumerate specific types of windows.

For each window, you can either:

or

  • use GetWindowModuleFileName() to query the window for the full path and filename of the module that created it (assuming the intended window is created by an actual EXE and not a DLL used by an EXE).

Once you have the window's filename, you can then compare that to your target filename.