Get time when window was last accessed (or activated)?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
omareg94
Posts: 94
Joined: 27 Jun 2016, 22:46

Get time when window was last accessed (or activated)?

Post by omareg94 » 26 Apr 2020, 03:17

Hello,

I'm looking for a way to get the time when a window was last accessed (or activated).

Let's say I activated (or accessed) a window 5 hours ago and I didn't activate it since this time (another window is currently activated).
Then, some arbitrarily-named function like getWindowLastActivateTime(my_window_id) should return 5 hours.
If I activated the window 3 minutes ago, it should return 3 minutes.
If the window is currently activated, it should return 0 minutes.
And so on.

Any approach that gets me nearer to a solution will be really helpful.

Rohwedder
Posts: 7774
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Get time when window was last accessed (or activated)?

Post by Rohwedder » 26 Apr 2020, 06:32

Hallo,
try:

Code: Select all

Global AktiveHwnd := {}
SetTimer, WinActive, 100
Return
q::my_window_id := WinActive("A")
w::ToolTip,% "was last activated " getWindowLastActivateTime(my_window_id) " seconds ago"
WinActive:
AktiveHwnd[WinActive("A")] := A_TickCount
Return
getWindowLastActivateTime(my_window_id)
{
	Return, (A_TickCount - AktiveHwnd[my_window_id])//1000
}

malcev
Posts: 1769
Joined: 12 Aug 2014, 12:37

Re: Get time when window was last accessed (or activated)?

Post by malcev » 26 Apr 2020, 06:45

Use SetWinEventHook or WinWaitActive+WinWaitNotActive in loop.

swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: Get time when window was last accessed (or activated)?

Post by swagfag » 26 Apr 2020, 10:16

Code: Select all

SetBatchLines -1
SetWinDelay -1

Run notepad.exe
WinWaitActive ahk_exe notepad.exe
Sleep 1000

MsgBox % WindowTracker.msElapsedSinceLastActivation(WinExist("ahk_exe notepad.exe"))

Process Close, notepad.exe

class WindowTracker
{
	static _ := WindowTracker.hook()
	static Hwnds := {}

	hook() {
		this.hook := DllCall("SetWinEventHook"
			, "UInt", 0x0003 ; EVENT_SYSTEM_FOREGROUND
			, "UInt", 0x0003 ; EVENT_SYSTEM_FOREGROUND
			, "Ptr", 0
			, "Ptr", RegisterCallback(this.foregroundChange, , , &this)
			, "UInt", 0 ; all process
			, "UInt", 0 ; all thread
			, "UInt", 0 ; WINEVENT_OUTOFCONTEXT
			, "Ptr")

		OnExit(this.unhook.Bind(this))
	}

	foregroundChange(event, hwnd, idObject, idChild, idEventThread, dwmsEventTime) {
		Object(A_EventInfo).Hwnds[hwnd] := A_TickCount
	}

	msElapsedSinceLastActivation(hwnd) {
		if !this.Hwnds.HasKey(hwnd)
			throw "hwnd not found"

		return A_TickCount - this.Hwnds[hwnd]
	}

	unhook() {
		DllCall("UnhookWinEvent", "Ptr", this.hook)
	}
}
swap out A_Tickcount for qpc if u need more granularity

Post Reply

Return to “Ask for Help (v1)”