Script Can't Wait for Two Things at Once

Get help with using AutoHotkey and its commands and hotkeys
Posts: 78
Joined: 10 Feb 2018, 19:05

Script Can't Wait for Two Things at Once

19 Jul 2020, 21:47

I'm trying to incorporate two mechanisms into a script: one to monitor when the RWin key is pressed, and another to monitor when an emulator window becomes active. I use two waiting loops to accomplish my task. Here's my code:

Code: Select all

SetBatchLines -1

GroupAdd Emulator, ahk_class EPSX
GroupAdd Emulator, ahk_class SDL_app
GroupAdd Emulator, ahk_class RetroArch

MsgBox Starting...

SetTimer MonitorRWin, -0
SetTimer MonitorEmulator, -0

Loop {
	KeyWait RWin, D
	DllCall("QueryPerformanceCounter", "Int64*", p)
	MsgBox % p
	KeyWait RWin
} return

Loop {
	WinWaitActive ahk_group Emulator
	WinGetClass EmulatorClass
	TrayTip Emulator Class, % EmulatorClass,, 16
	WinWaitNotActive ahk_group Emulator
	WinWaitNotActive ahk_class Shell_TrayWnd
} return
When I run the above script, only the waiting loop in the second timer works. I don't see anything in the documentation that says that a script can't wait for multiple things at the same time. Is this a bug, or just undocumented behavior?
User avatar
Posts: 6156
Joined: 21 Dec 2014, 02:44

Re: Script Can't Wait for Two Things at Once

20 Jul 2020, 00:36

It's neither a bug nor undocumented behavior since the documentation states that AHK does not have multi-threading capability (AHK_H does). What's happening is you have it launch MonitorRWin and MonitorEmulator right away. It starts with MonitorRWin which begins waiting for RWin to be pressed down, then it immediately gets interrupted by the other SetTimer routine (both are set to only run once) and the other one never returns from its loop, so it stays in that thread and the other thread never gets to continue executing. The above can be confirmed by viewing the recently executed lines (double-click the script's tray icon).

You could have both monitor things if you set a period for your SetTimers and you didn't put them in infinite loops (i.e., quickly check the status, act on it or not, and return). You can not have two infinite loops in separate threads be executing in parallel. You might consider using AHK_H if you need it to do that. Or you could run two separate scripts which each would be their own thread.

Return to “Ask For Help”

Who is online

Users browsing this forum: No registered users and 34 guests