Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which monitor the focus window is on?

Tags:

autohotkey

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.

like image 565
Anu Avatar asked Nov 07 '22 10:11

Anu


1 Answers

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
        }
    }
}
like image 87
Anu Avatar answered Nov 27 '22 23:11

Anu