Search code examples
windowsautohotkeypidexplorer

AHK find pid of explorer.exe?


This relates to this question.

How can I make an if statement in AutoHotKey which runs if the current application is not explorer.exe. This it to prevent the script from quitting explorer.exe, which it originally did (if I was on explorer).

Current script (which doesn't quit anything at all):

Pause::
WinGet,win_pid,PID,ProcessName,A
if (ProcessName != "explorer.exe") {
Run,taskkill /f /pid %win_pid%,,,
return
} else {
return
}

Original script (which successfully quits the last app, including explorer [if that was the last app]):

Pause::
WinGet,win_pid,PID,A
Run,taskkill /f /pid %win_pid%,,,
return

Solution

  • First the stuff that's wrong in your script:
    You're using WinGet with the sub-command PID.
    It takes the following parameters:
    WinGet, OutputVar, PID [, WinTitle, WinText, ExcludeTitle, ExcludeText]
    As you can see, the last two arguments you pass make no sense. You're trying to match a window with the title "ProcessName" and it also has to contain the text "A".
    If you wanted to get the process name, you'd use the intended WinGet sub-command for it like so:

    WinGet, output, ProcessName, A ;A, as a WinTitle, means the currently active window
    MsgBox, % output
    

    However, there's no need to go about it this way. There are way easier ways.
    I'll now show and explain the best way, creating a context sensitive hotkey by using #directives.
    Specifically the #IfWinNotActive is what you want to use.
    In the WinTitle parameter we can refer to the explorer window straight via its process name by the use of ahk_exe.

    #IfWinNotActive, ahk_exe explorer.exe
    Pause::
        WinGet, win_pid, PID, A
        Run, taskkill /f /pid %win_pid%
    return
    #IfWinNotActive
    

    And now we have a hotkey that will only trigger if the active window is not explorer.