Capture Window Events with AutoHotkey

I went looking for a way to capture window events in order to trigger actions when a specific event occurred and I came across this post with an AutoHotkey script that does just that. It’s necessary to know what shell message to look for when adding in your own code. This information is given by another AHK script located here.

With the shell information collected you can now add your own code to trigger certain actions on specified window events. Two ways that I’ve used so far to match window titles is as follows:
1) If (Title = “Windows”)
[autoit title=”If Statement”]
WinGetTitle, Title, ahk_id %lParam%
If (Title = “Windows”)
[/autoit]
2) IfInString, Title, Battlefield
[autoit title=”IfInString Statement”]
WinGetTitle, Title, ahk_id %lParam%
IfInString, Title, Battlefield
[/autoit]

Method #1 is fine most of the time unless the window title uses abstract characters. For example the Battlefield game window uses the title “Battlefield 3™”. If you paste that exact title into the script the if statement will evaluate to false. In order to get around this issue I used IfInString. While this fixed my initial problem a new problem appeared in its place which triggered the event when I launched the Battlelog website in my browser. To get around this I added another IfInString statement within the first that looked for the proper class.

[autoit title=”Nested IfInString Statement”]
WinGetTitle, Title, ahk_id %lParam%
WinGetClass, Class, ahk_id %lParam%

IfInString, Title, Battlefield
{
IfInString, Class, Battlefield
{
MsgBox, Success!
}
}
[/autoit]

To perform an action when a window is created use {autoit}If (wParam = 1){/autoit}
To perform an action when a window is destroyed use {autoit}If (wParam = 2){/autoit}

What I use the script for:
1) Triggering my Razer Game Booster hot keys to enter boost mode when Battlefield 3 is launched.
2) To close out of the “Windows has detected that your computer’s performance is slow” window.
3) To move program windows like Evernote to a specific location when their window is created.

[autoit title=”WatchWindows.ahk”]
#Persistent
SetBatchLines, -1
Process, Priority,, High

Gui +LastFound
hWnd := WinExist()

DllCall(“RegisterShellHookWindow”, UInt, hWnd)
MsgNum := DllCall(“RegisterWindowMessage”, Str, “SHELLHOOK”)
OnMessage(MsgNum, “ShellMessage”)
Return

ShellMessage(wParam, lParam)
{
If (wParam = 1) ; HSHELL_WINDOWCREATED := 1
{
WinGetTitle, Title, ahk_id %lParam%
WinGetClass, Class, ahk_id %lParam%
IfInString, Title, Battlefield
{
IfInString, Class, Battlefield
{
SendInput, ^!b
Sleep 1000
Run F:\Development\AutoHotkey\PauseSABnzbd.ahk
ExitApp
}
}
IfInString, Title, Evernote
WinMove, %Title%,, -1920, 0, 894, 1078
If (Title = “Windows”)
WinClose, ahk_id %lParam%
}
}
[/autoit]