Search code examples
godotgdscript

How can i detect opened programs in Godot3.1?


I want to detect, that is chrome opened, but I don't know, how to do that.

This is in a program, that detects how much my little brother watches YT videos.

Godot doesn't allow to get out of "user://"


Solution

  • If you have Windows 10 as operating system, you can call powershell from Godot to make it. In powershell, to get list of chrome process, use get-process chrome and you will see something like this:

        Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
        -------  ------    -----      -----     ------     --  -- -----------
        343      19    31404      57972       0,88   2664   2 chrome
        259      17    22972      43920       0,34   2972   2 chrome
        529      29    76956      65512       1,00   3576   2 chrome
        238      17    24148      46548       0,55   5480   2 chrome
        219      15    13084      23128       0,22   7676   2 chrome
        136      11     1992       8724       0,05   7924   2 chrome
        161       9     1676       6484       0,03  10200   2 chrome
        230      16    16504      33064       0,17  13252   2 chrome
        415      21    14372      30508       5,45  14836   2 chrome
        195    8717    44248      27944       0,75  15520   2 chrome
       1290      49    72020     129948      14,66  17652   2 chrome
    

    If you write get-process chrome | measure-object -line you can get the number of lines:

        Lines Words Characters Property
        ----- ----- ---------- --------
           11
    

    And, finally, if you write get-process chrome | measure-object -line | select Lines -expandproperty Lines you will see only the number of lines:

    11
    

    Now, apply this in Godot:

    func _is_chrome_active() -> bool:
        var chrome_active = false
        if OS.get_name() == "Windows": # Verify that we are on Windows
            var output = []
            # Execute "get-process" in powershell and save data in "output":
            OS.execute('powershell.exe', ['/C', "get-process chrome | measure-object -line | select Lines -expandproperty Lines"], true, output)   
            var result = output[0].to_int()
            chrome_active = result > 0    # If there is more than 0 chrome processes, it will be true
            print("Number of chrome processes: " + str(result))
        return chrome_active
    

    Here, it's used OS.execute to open powershell and send the command. The result, will be saved in the output variable as an Array. Take the first (and unique) element from the and transform it in a number with the line var result = output[0].to_int(). After, compare the value with 0 to know if is some chrome process in execution. This function returns true if there is some chrome process active and false if not.

    Now, you can call it from a Timer and count the time elapsed with chrome opened.