Making a key be pressed when another is unpressed (AHK)

i am working on this script.

#Persistent
Random , timerval , 7800 , 8460
SetTimer, PressTheKey,  %timerval%
Return

PressTheKey:
Send, {d}
Return

This is a basic interval for "d" to be pressed every 8~ seconds. It works. The problem is, if another key is being pressed, like Right Mouse Button, "d" won't be triggered and i'll have to wait the remaining duration.

I need to make the script wait for right mouse button to be unpressed, or to run a check every 10ms or so to check if the right mouse button is pressed or not, and if it isn't, it could Send, {d}.

So, i was thinking of using GetKeyState(), KeyWait or a While Loop to get over that.

#Persistent
Random , timerval , 7800 , 8460
SetTimer, PressTheKey,  %timerval%
Return

GetKeyState, state, RButton
if state = D
KeyWait, RButton

PressTheKey:
Send, {d}
Return

I tried this one and the others but i was not able to put it to work, not a expert in coding, but im trying to learn.

Can someone help me with this?

edit: holding down the key for a certain amout of time fixes this.

#Persistent
Random , timerval , 7800 , 8460
Random , timerval2 , 180 , 250
SetTimer, PressTheKey,  %timerval%
Return

PressTheKey:
Send, {t down}
Sleep, %timerval2%
Send, {t up}
Return

F1::
Pause
Suspend
return

Upvotes: 1

Views: 1046

Answers (2)

stevecody
stevecody

Reputation: 676

GetKeyState will not work in your AHK example the reason is, it is not insite the loops.

(the first Return will prevent that)

you can fix this with this example:

Example.ahk

;#notrayicon
#SingleInstance force
#Persistent
#MaxThreadsPerHotkey 10

Random , timerval , 7800 , 8460
SetTimer, PressTheKey,  %timerval%
Return



PressTheKey:
GetKeyState, state, RButton
if state = U
{
KeyWait, RButton
send {esc}
;ControlSend, , {esc}, ahk_exe NOTEPAD.EXE ;you can use this codeline for specific Application. 
}

Send, {d}
;ControlSend, , {d}, ahk_exe NOTEPAD.EXE ;you can use this codeline for specific Application. 
Return

f1::exitapp 

note - if you do Right Mouse click then the Cursor will be disapear into the popup-menu you can only fix this with the code line send {esc} or write a code line to focus cursor back to that window!

Upvotes: 1

user10364927
user10364927

Reputation:

You nearly had it.

#Persistent
Random , timerval , 7800 , 8460
SetTimer, PressTheKey,  %timerval%
Return

PressTheKey:
KeyWait, RButton, U
Send, {d}
Return

The only problem I can see is if the RButton is held down for longer than 2x the timer. In that case, I believe it will only trigger one extra Send, {d} as opposed to the total amount that it should. Anyway, that seems like an unlikely situation based on what you've said.

Upvotes: 0

Related Questions