简体   繁体   中英

Autohotkey: Define a hotkey and passthrough it to system dynamically, how to?

I'm facing a somewhat hard question. Look at this script:

; Using Autohotkey 1.1.36.2

F2:: 
send_f2_withcond()
{
    if(WinExist("ahk_class Notepad"))
    {
        ControlSend Edit1, % A_Now "`r", % "ahk_class Notepad"
    }
    else
    {
        ; I hope F2 can do its original action. How to?
        
        Send {$F2} ; ??? No effect!
    }
}

My purpose:

  • If there is Notepad running, F2 will send some text to Notepad.
  • If Notepad is not running, I hope F2 can do it original action, for example, pressing F2 in an Explorer window will start renaming current highlighted file.

Writing Send {F2} is not correct, because it will trigger my own F2:: ... action recursively.

The doc says adding a $ prefix will suppress recursive calling, BUT, Send {$F2} takes no effect(as if I totally omit this Send ), the current active application receives only F2's WM_KEYUP, no WM_KEYDOWN.

The $ prefix is used only in hotkey definitions. It forces the keyboard hook to be used, which is designed to filter out keys sent by AutoHotkey scripts.

$F2:: send_f2_withcond()

send_f2_withcond() {
    if WinExist("ahk_class Notepad")
        ControlSend, Edit1, % A_Now "`r", % "ahk_class Notepad"
    else   
        Send {F2}
}

You can greatly simplify this script by using #IfWinExist .

#IfWinExist, ahk_class Notepad
F2::ControlSend Edit1, % A_Now "`r", % "ahk_class Notepad"
#IfWinExist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM