2

I want to get the name of running application having the process name for e.g. pycharm64.exe-->Pycharm or chrome.exe --> Google chrome

Here's what I have achieved so far

import wmi
c = wmi.WMI()

def get_process_name(hwnd):
"""Get applicatin filename given hwnd."""
try:
    _, pid = win32process.GetWindowThreadProcessId(hwnd)

    for p in c.query('SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)):
        exe = p.Name
        # print(GetFileVersionInfo(exe))
        break
    return exe
except:
    return None


while True :
time.sleep(3) 
print(get_process_name(win32gui.GetForegroundWindow()))
  • Okay, and what does this return that is different from expected? – OneCricketeer Oct 07 '21 at 17:48
  • @OneCricketeer it returns the process name but I want the application name for further steps in the program. e.g. POWERPNT.EXE is what I get when PowerPoint is the running application – Mohamed Gamal Oct 07 '21 at 17:51
  • If you set a breakpoint on the `exe = P.Name` line, and look at all the other attributes of `p`, can you find what you want? – OneCricketeer Oct 07 '21 at 17:52
  • @OneCricketeer I tried this but there are only two other attributes Handle which returns the handle number and __len__ attribute – Mohamed Gamal Oct 07 '21 at 18:00
  • If you want the window title try (and google) `win32gui.GetWindowText(win32gui.GetForegroundWindow())` – viilpe Oct 07 '21 at 18:44
  • @viilpe The problem with this approach is that you don't get program name but you get title of window for e.g. if I tried to open a file in powerpoint what I get is "open" what I want is to get the program name itself "powerpoint" – Mohamed Gamal Oct 07 '21 at 19:13
  • @MohamedGamal ok [then take a look at this](https://stackoverflow.com/questions/580924/how-to-access-a-files-properties-on-windows). For PowerPoint: getFileProperties('path to exe')['StringFileInfo']['FileDescription'] -> 'Microsoft PowerPoint' – viilpe Oct 07 '21 at 20:16
  • I found a solution that works ! Using the file description I take the path of the process exe and then using win32api.GetFileVersionInfo I got the file description name as intended. here's the code : `p = psutil.Process(pid) ExecutablePath = p.exe() langs = win32api.GetFileVersionInfo(ExecutablePath, r'\VarFileInfo\Translation') key = r'StringFileInfo\%04x%04x\FileDescription' % (langs[0][0], langs[0][1]) description=(win32api.GetFileVersionInfo(ExecutablePath, key))` – Mohamed Gamal Oct 07 '21 at 20:34
  • Thanks @viilpe ! I found the same solution as yours :) maybe yours is a bit cleaner – Mohamed Gamal Oct 07 '21 at 20:40

0 Answers0