Small AHK function to determine which monitor the focus window is on.
I was writing a script that needed context on which monitor the focus window was on. I found quite a few solutions, but none were too easy to follow, or were a little more complex than needed.
Below will get you just that. The monitor Index in AHK so you can reference it.
GetFocusWindowMonitorIndex(){
;Get number of monitor
SysGet, monCount, MonitorCount
;Iterate through each monitor
Loop %monCount%{
;Get Monitor working area
SysGet, workArea, Monitor, % A_Index
;Get the position of the focus window
WinGetPos, X, Y, , , A
;Check if the focus window in on the current monitor index
if (X >= workAreaLeft && X < workAreaRight && Y >= workAreaTop && Y < workAreaBottom ){
;Return the monitor index since its within that monitors borders.
return % A_Index
}
}
}
Note Below is a modified version where the window is passed as an argument, and not the default; focus window
GetFocusWindowMonitorIndex(thisWindow){
;Get number of monitor
SysGet, monCount, MonitorCount
;Iterate through each monitor
Loop %monCount%{
;Get Monitor working area
SysGet, workArea, Monitor, % A_Index
;Get the position of the focus window
WinGetPos, X, Y, , , %thisWindow%
;Check if the focus window in on the current monitor index
if (X >= workAreaLeft && X < workAreaRight && Y >= workAreaTop && Y < workAreaBottom ){
;Return the monitor index since it's within that monitors borders.
return % A_Index
}
}
}
Even if this helps one more person, I'll call it a win.
EDIT:
Should you need the working area (exclude the tarkbar from the working area) use this functions.
GetFocusWindowMonitorIndex(){
;Get number of monitor
SysGet, monCount, MonitorCount
;Iterate through each monitor
Loop %monCount%{
;Get Monitor working area
SysGet, workArea, MonitorWorkArea , % A_Index
;Get the position of the focus window
WinGetPos, X, Y, , , A
;Check if the focus window in on the current monitor index
if (X >= workAreaLeft && X < workAreaRight && Y >= workAreaTop && Y < workAreaBottom ){
;Return the monitor index since its within that monitors borders.
return % A_Index
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With