Center Active Window Using AutoHotkey

A simple solution for centering windows across multiple monitors.

Managing windows across multiple displays can be cumbersome. While Windows offers basic snapping functionality, precisely centering windows requires manual repositioning. This post presents a concise AutoHotkey script that automates window centering with a simple keyboard shortcut.

The Script

Features:

; Center active window
#c::  {
    WinGetPos(&X, &Y, &W, &H, "A")
    CoordMode("Mouse", "Screen")
    MouseGetPos(&mouseX, &mouseY)
    monitorNumber := MonitorGetPrimary()

    ; Find which monitor the window is actually on
    Loop MonitorGetCount() {
        MonitorGetWorkArea(A_Index, &mLeft, &mTop, &mRight, &mBottom)
        if (X >= mLeft && X < mRight && Y >= mTop && Y < mBottom) {
            monitorNumber := A_Index
            break
        }
    }

    ; Calculate perfect center for THAT monitor
    MonitorGetWorkArea(monitorNumber, &monitorLeft, &monitorTop, &monitorRight, &monitorBottom)
    newX := monitorLeft + (monitorRight - monitorLeft - W) / 2
    newY := monitorTop + (monitorBottom - monitorTop - H) / 2
    WinMove newX, newY,,, "A"
}

Implementation Guide

  1. Install AutoHotkey v2+ (Download here).
  2. Save the script with a .ahk extension, such as CenterWindow.ahk.
  3. Execute the script by right-clicking and selecting “Run Script”. For persistent availability, add it to startup.

Customization Options

Known Limitations

How It Works

The script functions through three key mechanisms:

1. Position Detection

CoordMode("Mouse", "Screen")
MouseGetPos(&mouseX, &mouseY)

This establishes screen-level coordinates to handle multi-monitor setups properly.

2. Monitor Identification

Loop MonitorGetCount() {
    MonitorGetWorkArea(A_Index, &mLeft, &mTop, &mRight, &mBottom)
    if (X >= mLeft && X < mRight && Y >= mTop && Y < mBottom) {
        monitorNumber := A_Index
        break
    }
}

This loop determines which monitor contains the active window by comparing window coordinates against each display’s boundaries.

3. Centering Calculation

newX := monitorLeft + (monitorRight - monitorLeft - W) / 2
newY := monitorTop + (monitorBottom - monitorTop - H) / 2

These formulas calculate the optimal window position, accounting for usable screen area (excluding taskbars and docks) and window dimensions.

Conclusion

This lightweight AutoHotkey solution provides efficient window management across multiple displays. With a single keyboard shortcut, you can instantly center any window on its current monitor, eliminating manual repositioning.