pythonwin32gui

How to save this list of windows running application to json


I'm trying to list all the application running in my windows pc, i manage to list them all but in my json file i got 1 item how to save all of my running application to json?

here is the code:

import json

import win32gui



def list_window_names():
    def winEnumHandler(hwnd, ctx):
        if win32gui.IsWindowVisible(hwnd):
            app_list = [win32gui.GetWindowText(hwnd)]
            with open('application_running.json', 'w') as f:
                json.dump(list(app_list),f)
                print('Data Saved')
    win32gui.EnumWindows(winEnumHandler, None)
    
 

list_window_names()

i got one item in json file:

["Program Manager"]

but the application that runs in my windows pc is multiple how to solve this?


Solution

  • The problem is that EnumWindows loops through every window using the given function, so every window calls the function winEnumHandler. However, you are opening the same JSON file every time you save the window, thus the file is overwritten, and you see only one program.

    To solve this, I declare a global variable LIST_PROGRAMS. Every loop will append the window name to the list, and then I just simply save that list.

    import json
    import win32gui
    
    LIST_PROGRAMS = []
    
    def list_window_names():
        def winEnumHandler(hwnd, ctx):
            if win32gui.IsWindowVisible(hwnd):
                app_list = [win32gui.GetWindowText(hwnd)]
                global LIST_PROGRAMS
                LIST_PROGRAMS.append(list(app_list))
                print('Program added')
        win32gui.EnumWindows(winEnumHandler, None)
        with open('application_running.json', 'w') as f:
            json.dumps(LIST_PROGRAMS, f)
            print('Data Saved')
        
    list_window_names()