Page 1 of 1

Launching function on HOTKEY HOLD for specified time, else send normal key

Posted: 13 Jun 2019, 14:06
by tempuser
I searching whole day and can't find right, working answer.

I want to launch my function mToggler() only when holding Win keys (left or right) for more than 800 ms.
But on the other hand I want not to lose bringing Start Menu with this hotkey short tap nor other Win+<key> shortcuts (like Win+D for Show Desktop).

Because I working on an "module" script code this will be #included in other main AHK script file, so I define hotkey by Hotkey command, not :: hotkey definition:

Code: Select all

Hotkey, LWin, mToggler
and I would like to avoid labeling, because it can mess with auto-execute section in main script.

I tried many solutions but none working fine.
My last try was something like this, but there are some glitches:
- not work with shortcuts like Win+D
- multiple hold-hotkey fires, when hotkey is hold much longer than initial threshold time (e.g few seconds)

Code: Select all

mToggler()
{
	KeyWait, %A_ThisHotkey%, U T0.8
	If (!ErrorLevel) {					; short tap
		SoundBeep 2000, 50
		Send {%A_ThisHotkey% Down}
		Send {%A_ThisHotkey% Up}
	} else {							; hold detected
	SoundBeep 200, 200
	; ... rest of the function code ...
	}
}
	
Hotkey, LWin, mToggler
Can anyone advise that this is the best (or at least good and reliable) solution for hotkey hold detection?
And how modify it to fix above two glitches?

Re: Launching function on HOTKEY HOLD for specified time, else send normal key

Posted: 13 Jun 2019, 17:07
by Rohwedder
Hallo,
try:

Code: Select all

HotKey, LWin, mToggler
Return
mToggler()
{
	Send, {Blind}{%A_ThisHotKey% Down}{VK07 Down} ;prevent Start Menu
	T := A_TickCount + 800, K := -1
	While, (A_TickCount < T) And GetKeyState(A_ThisHotKey,"P")
	{
		Key := Format("VK{:X}",K := Mod(++K,256))
		IF GetKeyState(Key,"P") And !InStr(Keys, Key := GetKeyName(Key))
			Keys .= "{" Key "}" ;adds all pressed keys
	}
	Send, {Blind}{VK07 Up}{%A_ThisHotKey% Up}
	IF (A_TickCount < T)
	{ ; short tap
		IF Keys = {%A_ThisHotKey%} ;no other key pressed
			Send, %Keys% ;open Start Menu
		SoundBeep 2000, 50
	}
	Else
	{ ; hold detected
		SoundBeep 200, 200
		; ... rest of the function code ...
		KeyWait, %A_ThisHotKey%
	}
}

Re: Launching function on HOTKEY HOLD for specified time, else send normal key

Posted: 13 Jun 2019, 17:56
by tempuser
Wow, seems quite complicated.
I must analyze this line by line.

Thanks a lot!