'script configuration:
'the monitor splits (horizontal and vertical) need to be specified
'in MON_SPLIT_HORZ and MON_SPLIT_VERT.
'
'sample script configuration:
'your system has 3 monitors, and monitor 1 should be split in two vertically, and monitor 3 should be split in four (two horizontally
'and two vertically).
'the MON_SPLIT_HORZ and MON_SPLIT_VERT arrays would look like this:
'
'MON_SPLIT_HORZ = Array(1, 1, 2)
'MON_SPLIT_VERT = Array(2, 1, 2)

Option Explicit
Dim MON_SPLIT_HORZ, MON_SPLIT_VERT
MON_SPLIT_HORZ = Array()
MON_SPLIT_VERT = Array()

If UBound(MON_SPLIT_HORZ) = -1 Then
	MsgBox "You'll need to configure the script before using it for the first time. To do this, right-click the script and select Edit from the menu, then read the instructions at the top of the script.",, "VMonMaximizeWnd"
	WScript.Quit
End If

Const SHOWSTATE_NORMAL = 2
Const SHOWSTATE_MAXIMIZED = 3
Dim wnd, sys, mon, newLeft, newTop, newWidth, newHeight
Set wnd = CreateObject("UltraMon.Window")
If wnd.GetForegroundWindow() = True Then
	Dim splitX, splitY
	splitX = MON_SPLIT_VERT(wnd.Monitor - 1)
	splitY = MON_SPLIT_HORZ(wnd.Monitor - 1)
	
	If splitX = 1 And splitY = 1 Then
		'monitor isn't split, maximize/restore normally
		If wnd.ShowState = SHOWSTATE_MAXIMIZED Then
			'restore window
			wnd.ShowState = SHOWSTATE_NORMAL
		Else
			'maximize window
			wnd.ShowState = SHOWSTATE_MAXIMIZED
		End If
	Else
		'monitor is split
		Set sys = CreateObject("UltraMon.System")
		Set mon = sys.Monitors(wnd.Monitor - 1)
		
		Dim maxLeft, maxTop, maxWidth, maxHeight, offset, pos
		maxWidth = Int(mon.WorkWidth / splitX)
		offset = wnd.Left - mon.WorkLeft
		pos = 0
		If offset > 0 Then
			pos = Int(offset / maxWidth)
			If pos >= splitX Then pos = splitX - 1
		End If
		maxLeft = mon.WorkLeft + (pos * maxWidth)
		
		maxHeight = Int(mon.WorkHeight / splitY)
		offset = wnd.Top - mon.WorkTop
		pos = 0
		If offset > 0 Then
			pos = Int(offset / maxHeight)
			If pos >= splitY Then pos = splitY - 1
		End If
		maxTop = mon.WorkTop + (pos * maxHeight)
		
		'check if window is currently maximized
		Dim wndLeft, wndTop, wndWidth, wndHeight
		wndLeft = wnd.Left
		wndTop = wnd.Top
		wndWidth = wnd.Width
		wndHeight = wnd.Height
		
		If wnd.ShowState = SHOWSTATE_NORMAL And wndLeft = maxLeft And wndTop = maxTop And wndWidth = maxWidth And wndHeight = maxHeight Then
			'window is maximized, restore it
			newWidth = wndWidth * 0.9
			newHeight = wndHeight * 0.9
			newLeft = wndLeft + (wndWidth - newWidth) / 2
			newTop = wndTop + (wndHeight - newHeight) / 2
		Else
			'window isn't maximized, maximize it
			newWidth = maxWidth
			newHeight = maxHeight
			newLeft = maxLeft
			newTop = maxTop
		End If
		
		wnd.ShowState = SHOWSTATE_NORMAL
		wnd.Left = newLeft
		wnd.Top = newTop
		wnd.Width = newWidth
		wnd.Height = newHeight
	End If

	wnd.ApplyChanges 0
End If
