AutoHotKey run program on any key

2019-08-05 07:50发布

问题:

I'd like to run a program when any key is pressed with AutoHotKey

Something like:

AnyKey::Run, D:\my\program\to\run\on\any\key.bat

EDIT2: This code is working perfectly:

 #InstallKeybdHook

SetTimer, AnyKeyPressed, 100

AnyKeyPressed:
    if( A_TimeIdlePhysical < 100 ){
        Run, D:\my\program\to\run\on\any\key.bat
}

^!p::pause

回答1:

A simple solution:

#InstallKeybdHook  ; this MUST be called at the start of your script

AnyKeyPressed() ; returns a 1 if any keyboard key is pressed, else returns 0
{
    if( A_TimeIdlePhysical < 25 )
        return 1

return 0
}

Note this function will return 1 if any key is pressed OR being held down, so change your code appropriately.

What happens is; the #InstallKeybdHook will change the behaviour of A_TimeIdlePhysical to only look for keyboard events.



回答2:

You have to check A_TimeIdlePhysical periodically, not just once on script start:

#InstallKeybdHook
SetTimer, CheckActivity, 100
Exit

CheckActivity:
    if(A_TimeIdlePhysical < 100) {
        Run, myNastyPictureMaker.bat
        ExitApp
    }
return

You can use SetTimer for recurring tasks. The script stops when the first activity was detected; otherwise, it would take a picture every 100 ms (or whatever timeout you set).

P.S: I hope you only want to use such a script on your private PC and not some publically available computer...



回答3:

Use Input, AnyKey, L1 to wait for any key to be pressed. L1 means after one key was pressed, without a [end] key required. You can check the content of AnyKey, but don't really need to.



回答4:

Perhaps a list of known keys might work?

keys = ``1234567890-=qwertyuiop[]\asdfghjkl;'zxcvbnm,./
Loop Parse, keys
Run, D:\my\program\to\run\on\any\key.bat
return

This is what comes to mind.



回答5:

#Persistent
#InstallKeyBDHook
SetTimer, WaitingForKey, 100

Return

WaitingForKey:

    Input, LogChar, B I L1 V
    LogWord := LogWord . LogChar
        ToolTip, % LogWord
    ;Run, D:\my\program\to\run\on\any\key.bat
    LogWord:=
    Return


^!p::pause