Const SNAP_TO_MONITOR = False 'set this to True to ensure dialogs aren't placed between two monitors
Const INTERVAL = 2 'number of seconds the script waits before enumerating open windows again

Set sys = CreateObject("UltraMon.System")
Set wnd = CreateObject("UltraMon.Window")
Set wndParent = CreateObject("UltraMon.Window")

'create the two maps used to store positioned windows
Set arrAdd = CreateObject("Scripting.Dictionary")
Set arrLookup = CreateObject("Scripting.Dictionary")

Do While True
	'enumerate all application windows
	For Each w In wnd.GetAppWindows(True)
		If w.HWndParent <> 0 Then
			wndParent.HWnd = w.HWndParent
			
			move = True
			If arrLookup.Exists(w.HWnd) = True Then move = False
			arrAdd.Add w.HWnd, 0

			If move = True Then
				If SNAP_TO_MONITOR = False Then
					If w.Monitor <> wndParent.Monitor Then
						w.Monitor = wndParent.Monitor
						w.ApplyChanges 1 + 2 'WNDCHANGE_RESIZE_TO_FIT + WNDCHANGE_CLIP_TO_WORKSPACE
					End If
				Else
					Set parentMon = sys.Monitors(wndParent.Monitor - 1)
					parentLeft = parentMon.WorkLeft
					parentTop = parentMon.WorkTop
					parentRight = parentLeft + parentMon.WorkWidth
					parentBottom = parentTop + parentMon.WorkHeight

					dlgLeft = w.Left
					dlgTop = w.Top
					dlgRight = dlgLeft + w.Width
					dlgBottom = dlgTop + w.Height

					If dlgLeft < parentLeft Then
						w.Left = parentLeft
					ElseIf dlgRight > parentRight Then
						w.Left = parentRight - w.Width
					End If
					If dlgTop < parentTop Then
						w.Top = parentTop
					ElseIf dlgBottom > parentBottom Then
						w.Top = parentBottom - w.Height
					End If

					w.ApplyChanges 0
				End If
			End If
		End If
	Next

	'swap maps, then clear arrAdd. this way we don't have entries for windows which no longer exist
	Set temp = arrLookup
	Set arrLookup = arrAdd
	Set arrAdd = temp
	Set temp = Nothing
	arrAdd.RemoveAll

	WScript.Sleep INTERVAL * 1000
Loop

