Jump to content

Center application window in the current monitor


stoyan
 Share

Recommended Posts

Multi-monitor aware window centring function. Can handle various work area setups as outlined below:

pos.png.ce5e79be9fdcd563356697fc819efeb5

Those are the variants I've tested.

#include <Math.au3>
#include <WinAPI.au3>
#include <WinAPIConstants.au3>
#include <WinAPIGdi.au3>
#include <WinAPISys.au3>
#include <WindowsConstants.au3>

Func activeWindowCenter()

  Const $window = WinGetHandle('[ACTIVE]')
  Const $monitorInfo = _WinAPI_GetMonitorInfo(_WinAPI_MonitorFromWindow($window))
  Const $area[] = [DllStructGetData($monitorInfo[1], 1), DllStructGetData($monitorInfo[1], 3), DllStructGetData($monitorInfo[1], 2), DllStructGetData($monitorInfo[1], 4)]
  Const $size = WinGetPos($window)

  If @error Then
    Return
  EndIf

  If BitAND(_WinAPI_GetWindowLong($window, $GWL_STYLE), $WS_MAXIMIZE) Then
    Return
  EndIf

  Const $areaWidth = _Max($area[0], $area[1]) - _Min($area[0], $area[1])
  Const $windowOffsetX = ($areaWidth - $size[2]) / 2
  Const $x = _Min($area[0], $area[1]) + $windowOffsetX

  Const $areaHeight = _Max($area[2], $area[3]) - _Min($area[2], $area[3])
  Const $windowOffsetY = ($areaHeight - $size[3]) / 2
  Const $y = _Min($area[2], $area[3]) + $windowOffsetY

  WinMove($window, '', $x, $y, $size[2], $size[3], 2)

EndFunc

Here's simple usage:

; include the definition

HotKeySet('#o', 'activeWindowCenter')

While 1
  Sleep(1000)
WEnd

 

; Opt('MustDeclareVars', 1)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...