Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Executable name of a window

I try to get the name of executable name of all of my launched windows and my problem is that:

I use the method

UINT GetWindowModuleFileName(      
HWND hwnd,
LPTSTR lpszFileName,
UINT cchFileNameMax);

And I don't understand why it doesn't work.

Data which I have about a window are:
-HWND AND PROCESSID

The error is: e.g:

HWND: 00170628 
ProcessId: 2336        
WindowTitle: C:\test.cpp - Notepad++
GetWindowModuleFileName():  C:\test.exe

HWND: 00172138 
ProcessId: 2543        
WindowTitle: Firefox
GetWindowModuleFileName():  C:\test.exe

HWND: 00120358 
ProcessId: 2436        
WindowTitle: Mozilla Thunderbird
GetWindowModuleFileName():  C:\test.exe

Note: test.exe is the name of my executable file, but it is not the fullpath of Notepad++... and it make this for Mozilla Thunderbird too... I don't understand why

I use the function like this:

char filenameBuffer[4000];
if (GetWindowModuleFileName(hWnd, filenameBuffer, 4000) > 0)
{
    std::cout << "GetWindowModuleFileName(): " << filenameBuffer << std::endl;
}

Thank you for your response.

like image 783
Jaguar Avatar asked Mar 07 '10 19:03

Jaguar


People also ask

Where is my EXE file located?

If a shortcut to the program whose EXE you want to find isn't easily available, you can browse C:\Program Files or C:\Program Files (x86) on your machine to find the application's main program folder. Look for a folder with a name similar to the publisher of the program, or the name of the application itself.

Is Process name same as EXE name?

Remarks. The ProcessName property holds an executable file name, such as Outlook, that does not include the .exe extension or the path. It is helpful for getting and manipulating all the processes that are associated with the same executable file.

How can I get Hwnd from process id?

You can use EnumWindows and GetWindowThreadProcessId() functions as mentioned in this MSDN article.


1 Answers

The GetWindowModuleFileName function works for windows in the current process only.

You have to do the following:

  1. Retrieve the window's process with GetWindowThreadProcessId.
  2. Open the process with PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access rights using OpenProcess.
  3. Use GetModuleFileNameEx on the process handle.

If you really want to obtain the name of the module with which the window is registered (as opposed to the process executable), you can obtain the module handle with GetWindowLongPtr with GWLP_HINSTANCE. The module handle can then be passed to the aforementioned GetModuleFileNameEx.

Example:

TCHAR buffer[MAX_PATH] = {0};
DWORD dwProcId = 0; 

GetWindowThreadProcessId(hWnd, &dwProcId);   

HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ , FALSE, dwProcId);    
GetModuleFileName((HMODULE)hProc, buffer, MAX_PATH);
CloseHandle(hProc);
like image 183
avakar Avatar answered Oct 23 '22 11:10

avakar