If app was in focus in last x minutes?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
TheNomadicAspie
Posts: 140
Joined: 07 Jan 2020, 15:39

If app was in focus in last x minutes?

Post by TheNomadicAspie » 23 Jul 2021, 23:02

Is there a way to conditionally check if an app was in focus in the last x minutes?

I want to back-up my project folder every 30 minutes, but only if I'm actively using VS Code. I'm planning on running a .cmd batch file using AHK, and I know how to check if a window is in focus, but am unsure how to check if a window was in focus within a certain period of time. Should I use a variable with a dateTime object and use a while loop with a sleep delay to check if the app is currently in focus, and use that as the basis for the rest of the code?

Or is there a method that would simplify it?
safetycar
Posts: 435
Joined: 12 Aug 2017, 04:27

Re: If app was in focus in last x minutes?

Post by safetycar » 23 Jul 2021, 23:49

This code is untested, but it would be my general approach
Give it a look and check if it helps you.

Code: Select all

#Persistent

SetTimer, SuperviseVscodeActivity, 1000

return ; End of Auto-execute section.

SuperviseVscodeActivity() {
	static ActivityStats := []
	static LastSave := A_TickCount
	if (WinAcitve("ahk_exe vscode.exe"))
		ActivityStats.Push(A_TickCount)
	Last30mins := A_TickCount - 1000*60*30
	while (ActivityStats.Length() and ActivityStats[1] < Last30mins)
		ActivityStats.RemoveAt(1)
	if (ActivityStats.Length() > 60) { ; ~ 60 seconds seen open in last 30 mins.
		if (LastSave < Last30mins) {
			LastSave := A_TickCount
			; Save code.
		}
	}
}
Personally I'd prefer to initialize LastSave with a value of 0.
But that would but that would trigger the first save much sooner (the first time it meets the minimum activity needed).

Edit: Made #persistent and fixed typo.
TheNomadicAspie
Posts: 140
Joined: 07 Jan 2020, 15:39

Re: If app was in focus in last x minutes?

Post by TheNomadicAspie » 24 Jul 2021, 10:53

Thank you very much.
Post Reply

Return to “Ask for Help (v1)”