0

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
Sam
  • 157
  • 1
  • 10

1 Answers1

1

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.

0x464e
  • 5,948
  • 1
  • 12
  • 17
  • Thanks, this works for all apps except for GTA V. I've tried using `#IfWinActive, ahk_exe GTA5.exe` `Pause::` `Run, taskkill /f /im GTA5.exe`, but that didn't work. Is there any way to make this part work? – Sam Feb 05 '20 at 22:25
  • Maybe the active window for GTA isn't found under such a process. – 0x464e Feb 06 '20 at 03:24
  • I know that it is, as when I run taskkill /f /im GTA5.exe in CMD, it quits it. Also, I found something online that said that AHK scripts for GTA V need to be ran as admin, so I guess I'll try having the script run as admin at startup, and then see if it can quit GTA – Sam Feb 06 '20 at 03:45
  • The game exiting when GTA5.exe is killed doesn't mean the active window comes from that process. Bigger games like that tend to have multiple processes and other "weird" stuff. Maybe check by using the `ProcessName` sub-command. But try that admin thing, could very well be it as well. – 0x464e Feb 06 '20 at 04:52