WinClose

Closes the specified window.

WinClose , WinTitle, WinText, SecondsToWait, ExcludeTitle, ExcludeText

Parameters

WinTitle, WinText, ExcludeTitle, ExcludeText

If each of these is blank or omitted, the Last Found Window will be used. Otherwise, specify for WinTitle a window title or other criteria to identify the target window and/or for WinText a substring from a single text element of the target window (as revealed by the included Window Spy utility).

ExcludeTitle and ExcludeText can be used to exclude one or more windows by their title or text. Their specification is similar to WinTitle and WinText, except that ExcludeTitle does not recognize any criteria other than the window title.

Window titles and text are case-sensitive. By default, hidden windows are not detected and hidden text elements are detected, unless changed with DetectHiddenWindows and DetectHiddenText. By default, a window title must start with the specified WinTitle or ExcludeTitle to be a match, unless changed with SetTitleMatchMode.

SecondsToWait

If blank or omitted, the command will not wait at all. If 0, it will wait 500 ms. Otherwise, specify the number of seconds (can contain a decimal point or be an expression) to wait for the window to close. If the window does not close within that period, the script will continue.

Remarks

This command sends a close message to a window. The result depends on the window (it may ask to save data, etc.)

If a matching window is active, that window will be closed in preference to any other matching window. In general, if more than one window matches, the topmost (most recently used) will be closed.

This command operates only upon a single window except when WinTitle is ahk_group GroupName (with no other criteria specified), in which case all windows in the group are affected.

ErrorLevel is not set by this command, so use WinExist(), IfWinExist or WinWaitClose if you need to determine for certain that a window is closed.

While the command is in a waiting state, new threads can be launched via hotkey, custom menu item, or timer.

WinClose sends a WM_CLOSE message to the target window, which is a somewhat forceful method of closing it. An alternate method of closing is to send the following message. It might produce different behavior because it is similar in effect to pressing Alt+F4 or clicking the window's close button in its title bar:

PostMessage, 0x0112, 0xF060,,, WinTitle, WinText  ; 0x0112 = WM_SYSCOMMAND, 0xF060 = SC_CLOSE

If a window does not close via WinClose, you can force it to close with WinKill.

WinKill, WinWaitClose, Process, WinActivate, SetTitleMatchMode, DetectHiddenWindows, Last Found Window, WinExist(), WinActive(), WinWaitActive, WinWait, GroupActivate

Examples

If Notepad does exist, close it, otherwise close the calculator.

if WinExist("Untitled - Notepad")
    WinClose ; Use the window found by WinExist.
else
    WinClose, Calculator