If you want the focus to follow the mouse in a computer with multiple monitors, the proposed solutions (Activate a window by hovering over it with the mouse) are probably not enough or at least not the best option. I found quite frustrating the lost of focus while you are on the same screen. For example if the mouse cursor go slightly out of the window where you are typing, you suddenly loose the focus and another window is shown on top of the one you where working on.
To solve this problem the only solution that I found was to turn off the Activate a window by hovering over it with the mouse feature and use AutoHotKey (it's a free and open-source software) to activate the focus on the window under the mouse cursor but only when the mouse moves from one screen to another.
Here is the script that you can use to get this behavior:
#Persistent
CoordMode, Mouse, Screen
; Initialize a variable to keep track of the last active screen
lastActiveMonitor := 0
; Check the active screen every 500 ms
SetTimer, CheckScreen, 500
return
CheckScreen:
; Get mouse position and the screen where the mouse is visible
MouseGetPos, mouseX, mouseY
; Get the count of screens
SysGet, monitorCount, MonitorCount
; Loop through each screen to find the one containing the mouse
Loop, %monitorCount%
{
SysGet, monitor, Monitor, %A_Index%
if (mouseX >= monitorLeft && mouseX <= monitorRight && mouseY >= monitorTop && mouseY <= monitorBottom)
{
screenNumberContainingMouse := A_Index
break
}
}
; Check if mouse changed screen
if (lastActiveMonitor != screenNumberContainingMouse)
{
lastActiveMonitor := screenNumberContainingMouse
; Skip activation while dragging on another screen
if (GetKeyState("LButton", "P") )
{
;return
}
WinGet, windowList, List
Loop, %windowList%
{
classPrefix := "Shell"
hWnd := windowList%A_Index%
WinGetClass, class, ahk_id %hWnd%
VarSetCapacity(rect, 16)
DllCall("user32\GetWindowRect", "Ptr", hWnd, "Ptr", &rect)
windowLeft := NumGet(rect, 0, "Int")
windowTop := NumGet(rect, 4, "Int")
windowRight := NumGet(rect, 8, "Int")
windowBottom := NumGet(rect, 12, "Int")
;Check if mouse is inside the window rect
isInside := (mouseX >= windowLeft && mouseX <= windowRight) && (mouseY >= windowTop && mouseY <= windowBottom)
if(isInside)
{
topmostHWND := hWnd
;ToolTip %hWnd% %windowTitle% %class% %windowLeft% %windowTop% %windowRight% %windowBottom% %mouseX% %mouseY%
break
}
}
; Activate the topmost window on the monitor where the mouse is located
if (topmostHWND)
{
WinActivate, ahk_id %topmostHWND%
WinGetTitle, windowTitle, ahk_id %topmostHWND%
WinGetClass, class, ahk_id %topmostHWND%
;ToolTip Activated: hwnd %hwnd% windowTitle %windowTitle% class %class%
}
}
return