Kevin Montrose
Kevin Montrose

Reputation: 22601

QueryFullProcessImageName failing with valid HINSTANCE?

//window is an HWND
LPWSTR path = new WCHAR[1024];
DWORD  size = 1024;

GetWindowText(window, path, 1024);

HINSTANCE instance = (HINSTANCE)GetWindowLongPtr(window, GWLP_HINSTANCE);

QueryFullProcessImageName(instance, PROCESS_NAME_NATIVE, path, &size);

This code fails on the call to QueryFullProcessImageName(...) with an error code 6 [invalid handle]. GetWindowText succeeds, and GetWindowLong returns a non-zero HINSTANCE.

I'm pretty new to win32, so why this isn't working is beyond me. I believe both the HWND and HINSTANCE involved are valid...

Thanks

Upvotes: 2

Views: 4181

Answers (1)

Brian R. Bondy
Brian R. Bondy

Reputation: 347556

Main problem:

For the function: QueryFullProcessImageName, the first parameter is not an HINSTANCE, it is the process handle. They are different. To get the current process Id you should use GetCurrentProcessId. Then pass that into OpenProcess to get the process handle.


Other Problem:

You should be using GetWindowLongPtr above instead of GetWindowLong. Using GetWindowLong would likely cause problems on x64 systems.


How to find out what your problem is on your own:

After most Win32 functions fail, you can find out the reason why by using GetLastError.

So after the call to QueryFullProcessImageName please do this:

DWORD dwLastError = GetLastError();
LPVOID lpMsgBuf;
std::string strErrorMessage;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwLastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf,    0, NULL);
if (lpMsgBuf)
{
    strErrorMessage = (const TCHAR*)lpMsgBuf;
    LocalFree(lpMsgBuf);
}

You can also simply just call GetLastError() and lookup its return value here.

Upvotes: 5

Related Questions