Question

I'm using the the code below to get some information about running processes. However, I seem to be having trouble using the module names to preform the functions. For example, as soon as the below code gets to win32api.GetModuleHandle(fileName), it crashes stating that the specified module could not be found. Any suggestions as to how I might fix this? Thank you much!

Code:

processName = "MyProcess"
PROCESS_ALL_ACCESS = 0x1F0FFF
hwnd = win32ui.FindWindow(None, processName).GetSafeHwnd()
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
processHandle = win32api.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
modules = win32process.EnumProcessModules(processHandle)
for module in modules:
    fileName = win32process.GetModuleFileName(processHandle, module)
    print('{:08X}'.format(module))
    print(fileName)
    print(win32api.GetModuleHandle(fileName))

processHandle.close()

Edit:

The first answer made me realize my "the specified module could not be found" is a bit ambiguous. This is a win32 module error, not a python module error. Everything is imported into python fine (I just left out the imports for brevity). The problem is with the line print(win32api.GetModuleHandle(fileName)). The more detailed error is pywintypes.error: (126, 'GetModuleHandle', 'The specified module could not be found.')

Was it helpful?

Solution

The problem is that you're taking a handle from a different process, getting its filename, then asking for the same filename's handle in your process.

Unless you happen to have already opened the module in your process too, there is no such handle in your process. As the GetModuleHandle docs explain, "The module must have been loaded by the calling process" (that is, by you).

If you wanted to open the module, use LoadLibrary.

If you wanted the handle from the other process… well, you already have that. If you need to get a handle with different access rights or something, explain what it is you actually need to do, and it's probably doable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top