4
votes

I am trying to open and close a program (e.g. Notepad) with the same hokey in Windows, let's say Strg+Alt+X. So, when the program is closed I wish to open it with "X" and when it is open I wish to close it with "X".

This is really easy to do with two hotkeys, one to open and one to close the program. But I don't know how to tackle this for the same hotkey. Could someone point me in the right direction? Maybe this is possible with Autohotkey?

2

2 Answers

6
votes

I believe this is what you are looking for. I've created the StartClose method for future use if you want to make hotkeys for other applications as well. You can find window titles and classes using Window Spy, which is found by right clicking your AutoHotkey tray icon.

x::StartClose("ahk_class Notepad", "notepad.exe")

StartClose(title, exe)
{
    IfWinExist, %title%
        WinClose
    else
    {
        Run, %exe%
        WinActivate
    }
}
1
votes

Elliot's answer pointed me to the right direction (I'm completely new to AutoHotKey Syntax). His approach uses the Window Title which works well for programs that do not minimise to the system tray. But if you have a program like that, it is better to close it based on the process ID:

^!x::StartClose("XMouseButtonControl.exe")

StartClose(exe)
{
Process, Exist, %exe% ; check to see if program is running
If (ErrorLevel = 0) ; If program is not running -> Run
    {
    Run, %exe%
    }
Else ; If program is running, ErrorLevel = process id for the target program -> Close
    {
    Process, Close, %ErrorLevel%
    }
}