Hotkey Utility, and A_ThisHotkey Topic is solved

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
User avatar
Coiler
Posts: 114
Joined: 29 Nov 2020, 09:06

Hotkey Utility, and A_ThisHotkey

Post by Coiler » 08 Dec 2020, 20:34

If I build the following hotkey:

Code: Select all

Hotkey( "RShift", (ThisHotKey) => MyFunc(ThisHotKey) )

MyFunc(ThisHotKey)
{
	if( A_ThisHotkey != ThisHotKey )
		return ERROR( "Confusion!" )
}
..would (could) the error ever be tripped? I'm wondering what the difference is between these two variables. Or I guess I'm wondering what the point is in passing a hotkey parameter to the Hotkey callback if we already have a global variable that represents the last hot-key that was pressed (wondering why the devs added it at all)? Are there any circumstances where we would need the passed variable ThisHotKey over the global variable A_ThisHotkey ?

I'm still new to AHK scripting, so feel free to explain the obvious if it seems like I'm missing it.

Thanks for any details!

CptRootBeard
Posts: 26
Joined: 16 Nov 2020, 14:47
Contact:

Re: Hotkey Utility, and A_ThisHotkey  Topic is solved

Post by CptRootBeard » 09 Dec 2020, 15:24

Hello again! The main purpose of the callback is to take a snapshot of sorts, right? We need to remember which specific hotkey called the function.
Because it's global, we can't necessarily depend on A_ThisHotkey for this purpose. Other threads might alter the value before we use it.

Consider the following example derived from your code:
Run the code, then press RShift followed quickly by LShift.

Code: Select all

Hotkey( "RShift", (ThisHotKey) => MyFuncR(ThisHotKey) )
Hotkey( "LShift", (ThisHotKey) => MyFuncL(ThisHotKey) )

MyFuncR(ThisHotKey)
{
	sleep 3000
	if( A_ThisHotkey != ThisHotKey )
		throw Exception("Confusion!")
}

MyFuncL(ThisHotKey)
{
	if( A_ThisHotkey != ThisHotKey )
		throw Exception("Confusion!")
}
By the time the RShift thread reaches the if-statement, the LShift thread has already overwritten the value of A_ThisHotKey and we get a mismatch.
This is one of the reasons many people avoid using globals when they can.

User avatar
Coiler
Posts: 114
Joined: 29 Nov 2020, 09:06

Re: Hotkey Utility, and A_ThisHotkey

Post by Coiler » 09 Dec 2020, 17:25

Yes, that makes sense. I guess I was hoping AHK had some type of "context sensitive macro" thing going on, where things like A_ThisHotKey was sort of a macro that changes values based on where it is used (sort of like the __LINE__ macro in C). So simply using multiple keys simultaneously makes the variable unreliable? That's not good. I need to make some changes.

Thanks for the help!

Post Reply

Return to “Ask for Help (v2)”