API Reference

This part of the documentation covers all the interfaces of AutoHotkey.py. For parts where AutoHotkey.py depends on external libraries, we document the most important right here and provide links to the canonical documentation.

Clipboard

This section describes functions that work with the Windows clipboard.

ahkpy.get_clipboard() str[source]

Get text from the Windows clipboard.

Variable:

Clipboard

ahkpy.set_clipboard(value)[source]

Put text into the Windows clipboard.

Variable:

Clipboard

ahkpy.wait_clipboard(timeout: float = None) str[source]

Wait until the clipboard contains text and return it.

If there is no text in the clipboard after timeout seconds, then an empty string will be returned. If timeout is not specified or None, there is no limit to the wait time.

Command:

ClipWait

ahkpy.on_clipboard_change(func: Callable = None, *args, prepend_handler=False)[source]

Register func to be called on clipboard change.

On clipboard change, func will be called with the clipboard text as the clipboard argument.

The optional positional args will be passed to the func when it is called. If you want the callback to be called with keyword arguments use functools.partial().

If the optional prepend_handler argument is set to True, the func will be registered to be called before any other previously registered functions.

If func returns true, then the other clipboard handlers won’t be called.

If func is given, returns an instance of ClipboardHandler. Otherwise, the function works as a decorator:

@ahkpy.on_clipboard_change()
def handler(clipboard):
    print(clipboard.upper())

assert isinstance(handler, ahkpy.ClipboardHandler)
Command:

OnClipboardChange

class ahkpy.ClipboardHandler(func: Callable)[source]

This immutable object holds a function registered to be called on clipboard change.

Creating an instance of ClipboardHandler doesn’t register the function as a handler. Use the on_clipboard_change() function instead.

unregister()[source]

Unregister the clipboard handler and stop calling the function on clipboard change.

Exception

exception ahkpy.Error(message, what=None, extra=None, file=None, line=None)[source]

The runtime error that was raised in the AutoHotkey.

Contains the following attributes:

message

The error message.

what

The name of the command, function or label which was executing or about to execute when the error occurred.

extra

Additional information about the error, if available.

file

The full path of the AHK script file which contains the line where the error occurred.

line

The line number in the AHK script where the error occurred.

Flow

ahkpy.sleep(secs)[source]

Suspend execution of the calling thread for the given number of seconds.

During the wait, AHK checks its message queue and handles hotkeys and other callbacks.

Command:

Sleep

ahkpy.poll()[source]

Make AHK check its the message queue.

This can be used to force any pending interruptions to occur at a specific place rather than somewhere more random.

ahkpy.suspend()[source]

Disable all hotkeys and hotstrings.

Command:

Suspend, On

ahkpy.resume()[source]

Enable all hotkeys and hotstrings.

Command:

Suspend, Off

ahkpy.toggle_suspend()[source]

Toggle all hotkeys and hotstrings.

Command:

Suspend, Toggle

ahkpy.restart()[source]

Terminate the currently running instance of the script and start a new one.

Command:

Reload

ahkpy.output_debug(*objects, sep=' ')[source]

Send objects separated by sep to the debugger with OutputDebugString.

All non-keyword arguments are converted to strings with str().

Command:

OutputDebug

ahkpy.coop(func, *args, **kwargs)[source]

Run the given function in a new thread and make it cooperate with AHK’s event loop.

Use coop() to execute long-running I/O bound Python processes like HTTP servers and stdin readers that are designed to handle KeyboardInterrupt:

import code
ahkpy.coop(code.interact)

This call runs the given function in a new thread and waits for the function to finish. Returns the function result or raises the exception.

Whenever KeyboardInterrupt occurs in the main thread, it’s propagated to the background thread so it could stop.

Calling coop() from a background thread doesn’t start a new one. Instead, the given function is executed in the current thread.

ahkpy.flow.ahk_call(cmd: str, *args)[source]

Call the arbitrary AHK command/function cmd with args arguments.

Use this function when there’s no appropriate AutoHotkey.py API.

GUI

Message Boxes

ahkpy.message_box(text=None, title=None, *, buttons='ok', icon=None, default_button=1, options=[], timeout=None) str | None[source]

Display the specified text in a small window containing one or more buttons.

Parameters:
  • text (str) – the text to display in the message box. Defaults to “Press OK to continue.”.

  • title (str) – the title of the message box window. Defaults to the name of the AHK script (without path), that is, “Python.ahk”.

  • buttons (str) –

    the buttons to display in the message box. Defaults to OK button. Takes one of the following values:

    • "ok"

    • "ok_cancel"

    • "yes_no_cancel"

    • "yes_no"

    • "retry_cancel"

    • "cancel_try_continue"

  • icon (str) –

    the icon to display. Defaults to no icon. Takes one of the following values:

    • None – no icon

    • "info", "information", "asterisk" – a symbol consisting of a lowercase letter i in a circle

    • "warning", "exclamation" – a symbol consisting of an exclamation point in a triangle with a yellow background

    • "error", "hand", "stop" – a symbol consisting of a white X in a circle with a red background

  • default_button (int) – which button should be focused when the message box is shown. Defaults to the first button in the reading order. Takes integer values from 1 to 3.

  • options (list[str]) –

    a list of zero or many of the following options:

    • "right" – the message box text is right-aligned

    • "rtl_reading" – specifies that the message box text is displayed with right to left reading order

    • "service_notification" – the message box is displayed on the active desktop

    • "default_desktop_only" – the message box is displayed on the active desktop. This is similar to "service_notification", except that the system displays the message box only on the default desktop of the interactive window station

  • timeout (float) – specifies time in seconds to wait for user’s response. After the timeout elapses, the message box will be automatically closed. If timeout is not specified or None, there is no limit to the wait time.

Returns:

None if the timeout has elapsed, or one of the following values that signify the button the user has pressed:

  • "ok"

  • "yes"

  • "no"

  • "cancel"

  • "abort"

  • "ignore"

  • "retry"

  • "continue"

  • "try_again"

Command:

MsgBox

class ahkpy.MessageBox(text=None, title=None, buttons='ok', icon=None, default_button=1, options=[], timeout=None)[source]

The utility object to reuse and show message boxes.

For information about the arguments refer to message_box().

The object can be used by setting the message box attributes and calling the show() method:

mb = ahkpy.MessageBox(text="hello")  # Doesn't show the message box yet
mb.text = "hello from attribute"
mb.show()  # Shows a message box with the text "hello from attribute"
mb.show(text="hello from keyword argument")
# ^^ Shows a message box with the text "hello from keyword argument"

Also, the class can be used by calling its static methods:

ahkpy.MessageBox.info("hello from the static method")
# ^^ Shows a message box with the "info" icon
show(text=None, title=None, **attrs)[source]

Show the message box with the given attributes.

static info(text, title=None, *, buttons='ok', default_button=1, **attrs)[source]

Show an info message.

static warning(text, title=None, *, buttons='ok', default_button=1, **attrs)[source]

Show a warning message.

static error(text, title=None, *, buttons='ok', default_button=1, **attrs)[source]

Show an error message.

static ok_cancel(text, title=None, *, icon='info', default_button=1, **attrs)[source]

Ask if operation should proceed; return True if the answer is ok.

static yes_no(text, title=None, *, icon='info', default_button=1, **attrs)[source]

Ask a question; return True if the answer is yes.

static yes_no_cancel(text, title=None, *, icon='info', default_button=1, **attrs)[source]

Ask a question; return "yes", "no", or "cancel".

static retry_cancel(text, title=None, *, icon='warning', default_button=1, **attrs)[source]

Ask if operation should be retried; return True if the answer is yes.

static cancel_try_continue(text, title=None, *, icon='warning', default_button=2, **attrs)[source]

Ask a question; return "cancel", "try", or "continue".

Tooltips

class ahkpy.ToolTip(text=None, *, x=None, y=None, relative_to='window', timeout=None)[source]

The tooltip object.

No more than 20 tooltips can be shown simultaneously.

Example usage:

tt = ToolTip(text="hello")  # Doesn't show the tooltip yet
tt.text = "hello from attribute"
tt.show()
# ^^ Shows a tooltip with the text "hello from attribute" near the mouse
# cursor
tt.show(text="hello from keyword argument")
# ^^ Hides the previous tooltip and shows a new one with the text "hello
# from keyword argument" near the mouse cursor
show(text=None, *, x=UNSET, y=UNSET, relative_to=None, timeout=UNSET)[source]

Show the tooltip.

If the method is called without the x and y arguments, the menu is shown at the mouse cursor.

Otherwise, the tooltip’s position depends on the relative_to argument. Valid relative_to values are:

  • "screen" – coordinates are relative to the desktop (entire screen).

  • "window" – coordinates are relative to the active window.

  • "client" – coordinates are relative to the active window’s client area, excluding title bar, menu and borders.

The optional x and y arguments set the tooltip’s position relative to the area specified by the relative_to argument. The default relative_to value is "window". So if you call tooltip.show("hello", x=42), the y coordinate will be the mouse cursor’s y coordinate, and the x coordinate will be 42 pixels to the right of the active window.

The text argument is required to either be set as the instance attribute, or passed as an argument.

If the optional timeout argument is given, the tooltip will be hidden after this many seconds.

Command:

ToolTip

hide()[source]

Hide the tooltip.

Window Messages

ahkpy.on_message(msg_number: int, func=None, *args, max_threads=1, prepend_handler=False)[source]

Register func to be called on window message msg_number.

Upon receiving a window message, the func will be called with the following arguments:

Parameters:
  • w_param (int) – the message’s wParam value

  • l_param (int) – the message’s lParam value

  • msg (int) – the message number, which is useful in cases where a function monitors more than one message

  • hwnd (int) – the HWND (unique ID) of the window or control to which the message was sent

The optional positional args will be passed to the func when it is called. If you want the callback to be called with keyword arguments use functools.partial().

The optional max_threads argument sets the number of messages AHK can handle concurrently.

If the optional prepend_handler argument is set to True, the func will be registered to be called before any other functions previously registered for msg_number.

If func is given, returns an instance of MessageHandler. Otherwise, the function works as a decorator:

WM_CLOSE = 0x0010

@ahkpy.on_message(WM_CLOSE)
def handler(w_param, l_param, msg, hwnd):
    print("was asked to close")

assert isinstance(handler, ahkpy.MessageHandler)
Command:

OnMessage

class ahkpy.MessageHandler(msg_number: int, func: Callable)[source]

This immutable object holds a function registered to be called upon receiving a window message.

Creating an instance of MessageHandler doesn’t register the function as a handler. Use the on_message() function instead.

unregister()[source]

Unregister the message handler.

Keyboard and Mouse

Hotkeys and Hotstrings

class ahkpy.HotkeyContext(active_when: Callable = None, *args)[source]

The hotkey, hotstring, and key remappings immutable factory.

If the active_when argument is a callable, it is executed every time the user triggers the hotkey or hotstring. The callable takes either zero arguments or a hot_id argument. The argument is the identifier of the triggered utility. For hotkeys, the identifier will be the key_name of the Hotkey that was pressed by the user. For hotstrings, the identifier will be the full AutoHotkey hotstring with packed options. The hotkey/hotstring action is executed only if the callable returns True.

The optional positional args will be passed to the active_when when it is called. If you want the active_when to be called with keyword arguments use functools.partial().

In the following example pressing the F1 key shows the message only when the mouse cursor is over the taskbar:

def is_mouse_over_taskbar():
    return ahkpy.get_window_under_mouse().class_name == "Shell_TrayWnd"

ctx = ahkpy.HotkeyContext(is_mouse_over_taskbar)
ctx.hotkey("F1", ahkpy.message_box, "Pressed F1 over the taskbar.")
Command:

Hotkey, If, % FunctionObject

hotkey(key_name: str, func: Callable = None, *args, **options)

Register func to be called when key_name is pressed.

For valid key_name values refer to Hotkey Modifier Symbols and List of Keys.

When the hotkey is triggered, func is called with the Hotkey instance as the hotkey argument if the function supports it:

ahkpy.hotkey("F1", lambda hotkey: print(hotkey))

Pressing F1 prints the following:

Hotkey(key_name='F1', context=HotkeyContext(active_when=None))

The optional positional args will be passed to the func when it is called. If you want the func to be called with keyword arguments use functools.partial().

The following keyword-only arguments set the hotkey options:

Parameters:
  • buffer (bool) – causes the hotkey to buffer rather than ignore keypresses when the max_threads limit has been reached. Defaults to False.

  • priority (int) – the priority of the AHK thread where func will be executed. It must be an integer between -2147483648 and 2147483647. Defaults to 0.

  • max_threads (int) – the number of keypresses AHK can handle concurrently. Defaults to 1.

  • input_level (int) – the input level of the hotkey. Defaults to 0.

If func is given, returns an instance of Hotkey. Otherwise, the method works as a decorator:

@ahkpy.hotkey("F1")
def hello():
    ahk.message_box("Hello!")

assert isinstance(hello, ahkpy.Hotkey)
Command:

Hotkey

remap_key(origin_key, destination_key, *, mode=None, level=None)

Remap origin_key to destination_key.

Returns an instance of RemappedKey.

For valid keys refer to List of Keys.

The optional keyword-only mode and level arguments are passed to the send() function that will send the destination_key when the user presses the origin_key.

For more information refer to Remapping Keys.

hotstring(trigger: str, repl: str | Callable = None, *args, **options)

Register a hotstring.

By default, the hotstring is triggered when the user types the given trigger text and presses one of the end chars which initially consist of the following: -()[]{}':;"/\,.?!\n \t. If repl is an instance of str, the user’s input will be replaced with repl. If repl is a callable, it will be called when the hotstring is triggered.

When the hotstring is triggered and repl is a callable, repl is called with the Hotstring instance as the hotstring argument if the function supports it.

The optional positional args will be passed to the repl when it is called. If you want the repl to be called with keyword arguments use functools.partial().

To change the end chars use the set_hotstring_end_chars() function.

The following keyword-only arguments set the hotstring options:

  • case_sensitive – if true, the user must type the text with the exact case to trigger the hotstring. Defaults to False.

  • conform_to_case – if false, the replacement is typed exactly as given in repl. Otherwise, the following rules apply:

    • If the user types the trigger text in all caps, the replacement text is produced in all caps.

    • If the user types the first letter in caps, the first letter of the replacement is also capitalized.

    • If the user types the case in any other way, the replacement is produced exactly as given in repl.

    Defaults to True for case-insensitive hotstrings. Conversely, case-sensitive hotstrings never conform to the case of the trigger text.

  • replace_inside_word – if true, the hotstring will be triggered even when it is inside another word; that is, when the character typed immediately before it is alphanumeric:

    ahkpy.hotstring("al", "airline",
                    replace_inside_word=True)
    

    Given the code above, typing “practical “ produces “practicairline “.

    Defaults to False.

  • wait_for_end_char – if false, an end chars is not required to trigger the hotstring. Defaults to True.

  • omit_end_char – if true and wait_for_end_char is true, then the hotstring waits for the user to type an end char and produces the replacement with the end char omitted. Defaults to False.

  • backspacing – if false, skips removing the user input that triggered the hotstring before producing the repl:

    ahkpy.hotstring("<em>", "</em>{Left 5}",
                    wait_for_end_char=False,
                    backspacing=False)
    

    Given the code above, typing <em> produces <em>|</em>, where | is the keyboard cursor.

    Defaults to True.

  • priority (int) – the priority of the AHK thread where repl will be executed if it’s a callable. It must be an integer between -2147483648 and 2147483647. Defaults to 0.

  • text – if true, sends the replacement text raw, without translating each character to a keystroke. For details, see Text mode. Defaults to False.

  • mode – the method by which auto-replace hotstrings send their keystrokes. Defaults to one currently set in Settings.send_mode. For the list of valid modes refer to send().

  • key_delay (float) – the delay between keystrokes produced by auto-backspacing and auto-replacement. Defaults to 0 for Event and Play modes. For more information refer to send().

  • reset_recognizer – if true, resets the hotstring recognizer after each triggering of the hotstring. To illustrate, consider the following hotstring:

    @ahkpy.hotstring(
        "11",
        backspacing=False,
        wait_for_end_char=False,
        replace_inside_word=True,
    )
    def eleven():
        ahkpy.send_event("xx", level=0)
    

    Since the above lacks the reset_recognizer option, typing 111 (three consecutive 1’s) triggers the hotstring twice because the middle 1 is the last character of the first triggering but also the first character of the second triggering. By setting reset_recognizer to True, you would have to type four 1’s instead of three to trigger the hotstring twice.

    Defaults to False.

If repl is given, returns an instance of Hotstring. Otherwise, the method works as a decorator.

Command:

Hotstring

ahkpy.default_context

The default instance of HotkeyContext.

ahkpy.hotkey(...)[source]
ahkpy.hotstring(...)[source]
ahkpy.remap_key(...)[source]

Useful aliases for default_context.hotkey(), default_context.hotstring(), and default_context.remap_key().

class ahkpy.Hotkey(key_name: str, context: ahkpy.HotkeyContext)[source]

The immutable object representing a hotkey registered in the given context.

Creating an instance of Hotkey doesn’t register it in AHK. Use the HotkeyContext.hotkey() method instead.

enable()[source]

Enable the hotkey.

disable()[source]

Disable the hotkey.

toggle()[source]

Enable the hotkey if it’s disabled or do the opposite.

update(*, func=None, buffer=None, priority=None, max_threads=None, input_level=None)[source]

Update the hotkey callback and options.

For more information about the arguments refer to HotkeyContext.hotkey().

class ahkpy.RemappedKey(origin_hotkey: ahkpy.Hotkey, origin_up_hotkey: ahkpy.Hotkey)[source]

The immutable object that represents a remapped key.

Creating an instance of RemappedKey doesn’t register it in AHK. Use the HotkeyContext.remap_key() method instead.

enable()[source]

Enable the key remapping.

disable()[source]

Disable the key remapping.

toggle()[source]

Enable the key remapping if it’s disabled or do the opposite.

class ahkpy.Hotstring(trigger: str, case_sensitive: bool, replace_inside_word: bool, context: ahkpy.HotkeyContext)[source]

The immutable object that represents a registered hotstring.

Creating an instance of Hotstring doesn’t register it in AHK. Use the HotkeyContext.hotstring() method instead.

Hotstrings in AutoHotkey are defined by the trigger string, case-sensitivity, word-sensitivity (replace_inside_word), and the context in which they are created. For example, the following creates only one hotstring:

hs1 = ahkpy.hotstring("btw", "by the way", case_sensitive=False)
hs2 = ahkpy.hotstring("BTW", "by the way", case_sensitive=False)

This is because case_sensitive option is set to False (the default), so that the hotstring will trigger regardless of the case it was typed in.

Conversely, the following creates two separate hotstrings:

hs1 = ahkpy.hotstring("btw", "by the way", case_sensitive=True)
hs2 = ahkpy.hotstring("BTW", "by the way", case_sensitive=True)
enable()[source]

Enable the hotkey.

disable()[source]

Disable the hotkey.

toggle()[source]

Enable the hotstring if it’s disabled or do the opposite.

update(*, repl=None, conform_to_case=None, wait_for_end_char=None, omit_end_char=None, backspacing=None, priority=None, text=None, mode=None, key_delay=None, reset_recognizer=None)[source]

Update the hotstring’s repl and options.

For more information about the arguments refer to HotkeyContext.hotstring().

ahkpy.reset_hotstring()[source]

Reset the hotstring recognizer.

The script will begin waiting for an entirely new hotstring, eliminating from consideration anything the user has typed previously.

Command:

Hotstring(“Reset”)

ahkpy.get_hotstring_end_chars()[source]

Retrieve the set of end chars.

The default end chars are the following: -()[]{}':;"/\,.?!\n \t.

Command:

Hotstring(“EndChars”)

ahkpy.set_hotstring_end_chars(chars: str)[source]

Change the end chars.

The end chars can only be changed globally for all hostrings at once.

Command:

Hotstring(“EndChars”, NewValue)

ahkpy.get_hotstring_mouse_reset()[source]

Get whether mouse clicks reset the hotstring recognizer.

By default, any click of the left or right mouse button will reset the hotstring recognizer.

Command:

Hotstring(“MouseReset”)

ahkpy.set_hotstring_mouse_reset(value: bool)[source]

Set whether mouse clicks reset the hotstring recognizer.

Command:

Hotstring(“MouseReset”, NewValue)

Sending

ahkpy.send(keys: str, *, mode=None, **options)[source]

Send simulated keystrokes and mouse clicks to the active window.

The keys argument is an encoded sequence of keys. For valid keys refer to Send.

Parameters:
Command:

Send

ahkpy.send_event(keys, **options)[source]
ahkpy.send_input(keys, **options)[source]
ahkpy.send_play(keys, **options)[source]

Send simulated keystrokes and mouse clicks using the corresponding mode.

For arguments refer to send().

Mouse

ahkpy.click(button='left', times=1, **options)[source]

Click a mouse button.

The button argument takes one of the following values: "left", "right", "middle", "x1", "x2".

The times argument specifies the number of times to click the mouse.

The following keyword-only arguments set the click options:

Parameters:
  • modifier (str) – the string of AHK characters that represent the keyboard modifiers to press down before clicking the mouse. Takes a combination of the following characters: !+^# which correspond to Alt, Shift, Ctrl, and Win. Defaults to no modifiers.

  • blind (bool) – if true, preserves the keyboard modifiers in the down position. For example, calling click() with Ctrl held down will send a Ctrl + Click. If false, releases the currently held keyboard modifiers before the click. Defaults to True.

  • mode (str) – the mode that is used to send the clicks. For more information refer to the mode argument of the send() function.

  • level (int) – controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings. For more information refer to the level argument of the send() function.

  • delay (float) – the delay after each mouse click. For more information refer to the mouse_delay argument of the send() function.

Command:

Send, {Click}

ahkpy.mouse_press(button='left', times=1, **options)[source]

Press down and hold a mouse button.

For arguments refer to click().

ahkpy.mouse_release(button='left', times=1, **options)[source]

Release a mouse button.

For arguments refer to click().

ahkpy.right_click(times=1, **options)[source]

Click the right mouse button.

For arguments refer to click().

ahkpy.double_click(button='left', **options)[source]

Double-click a mouse button.

For arguments refer to click().

ahkpy.mouse_scroll(direction: str, times=1, **options)[source]

Scroll the mouse wheel.

The direction argument specifies the scroll direction. Takes one of the following values: "up", "down", "left", "right".

The times argument specifies the number of notches to turn the wheel. However, some applications do not obey times higher than 1. Use the following workaround:

for _ in range(5):
    ahkpy.mouse_scroll("up")

For the options arguments refer to click().

Command:

Send, {Click}

ahkpy.mouse_move(x, y, *, relative_to='window', mode=None, speed=None, delay=None)[source]

Move the mouse cursor.

The x and y arguments set the coordinates to move the mouse relative to the area specified by the relative_to argument which defaults to "window". The valid relative_to arguments are the following:

  • "cursor" – coordinates are relative to its current position.

  • "screen" – coordinates are relative to the desktop (entire screen).

  • "window" – coordinates are relative to the active window.

  • "client" – coordinates are relative to the active window’s client area, which excludes the window’s title bar, menu (if it has a standard one) and borders. Client coordinates are less dependent on OS version and theme.

Parameters:
  • mode (str) – the mode that is used to move the mouse. If the speed argument is given, it forces the Event mode. For more information refer to the mode argument of the send() function.

  • speed (int) – the speed of mouse movement in the range 0 (fastest) to 100 (slowest). Defaults to one currently set in Settings.mouse_speed.

  • delay (float) – the delay after the mouse movement. For more information refer to the mouse_delay argument of the send() function.

Command:

Send, {Click X, Y, 0}, MouseMove

The MouseClickDrag command can be implemented as follows:

ahkpy.mouse_move(x=x1, y=y1)
ahkpy.mouse_press(which_button)
ahkpy.mouse_move(x=x2, y=y2, speed=speed, relative_to=...)
ahkpy.mouse_release()
ahkpy.get_mouse_pos(relative_to='window') Tuple[int, int][source]

Get current mouse position relative to specified area.

The valid relative_to arguments are the following:

  • "screen" – coordinates are relative to the desktop (entire screen).

  • "window" – coordinates are relative to the active window.

  • "client" – coordinates are relative to the active window’s client area, which excludes the window’s title bar, menu (if it has a standard one) and borders. Client coordinates are less dependent on OS version and theme.

Returns a (x, y) tuple.

Command:

MouseGetPos, X, Y

ahkpy.get_window_under_mouse() ahkpy.Window[source]

Get the window under the mouse cursor.

Returns a Window instance. If the window cannot be determined, returns Window(None). The window does not have to be active to be detected.

Command:

MouseGetPos,,, Win

ahkpy.get_control_under_mouse(simple=False) ahkpy.Control[source]

Get the control under the mouse cursor.

If the simple argument is true, a simpler method of detection is used. This method correctly retrieves the active/topmost child window of an Multiple Document Interface (MDI) application such as SysEdit or TextPad. However, it is less accurate for other purposes such as detecting controls inside a GroupBox control.

Returns a Control instance. If the control cannot be determined, returns Control(None). The window does not have to be active for the control to be detected.

Command:

MouseGetPos,,,, Control

ahkpy.get_cursor_type() str[source]

Get the type of mouse cursor currently being displayed.

Returns one of the following words: AppStarting, Arrow, Cross, Help, IBeam, Icon, No, Size, SizeAll, SizeNESW, SizeNS, SizeNWSE, SizeWE, UpArrow, Wait, Unknown.

The acronyms used with the size-type cursors are compass directions, e.g. NESW is NorthEast+SouthWest. The hand-shaped cursors (pointing and grabbing) are classified as Unknown.

Key States

In the following functions, the key_name argument is a VK or SC code, such as "vkA2" or "sc01D", a combination of both, or a key from the key list.

ahkpy.get_key_name(key_name: str) str[source]

Return the name of a key.

>>> ahkpy.get_key_name("vk70")
'F1'
>>> ahkpy.get_key_name(f"vk{112:x}")
'F1'
>>> ahkpy.get_key_name("sc3b")
'F1'
Command:

GetKeyName

ahkpy.get_key_name_from_vk(vk: int) str[source]

Return the name of a key given its virtual key code.

>>> ahkpy.get_key_name_from_vk(112)
'F1'
Command:

GetKeyName

ahkpy.get_key_name_from_sc(sc: int) str[source]

Return the name of a key given its scan code.

>>> ahkpy.get_key_name_from_sc(59)
'F1'
Command:

GetKeyName

ahkpy.get_key_vk(key_name: str) int[source]

Return the virtual key code of a key.

>>> ahkpy.get_key_vk("F1")
112
Command:

GetKeyVK

ahkpy.get_key_sc(key_name: str) int[source]

Return the scan code of a key.

>>> ahkpy.get_key_sc("F1")
59
Command:

GetKeySC

ahkpy.is_key_pressed(key_name: str) bool[source]

Return whether the key is pressed down physically.

Command:

GetKeyState

ahkpy.is_key_pressed_logical(key_name: str) bool[source]

Return the logical state of the key.

This is the state that the OS and the active window believe the key to be in, but is not necessarily the same as the physical state, that is, whether the user is physically holding it down.

Command:

GetKeyState

ahkpy.wait_key_pressed(key_name, timeout: float = None) bool[source]
ahkpy.wait_key_released(key_name, timeout: float = None) bool[source]
ahkpy.wait_key_pressed_logical(key_name, timeout: float = None) bool[source]
ahkpy.wait_key_released_logical(key_name, timeout: float = None) bool[source]

Wait for a key or mouse/joystick button to be pressed/released physically/logically.

Returns True when the user presses the key. If there is no user input after timeout seconds, then False will be returned. If timeout is not specified or None, there is no limit to the wait time.

The logical state is the state that the OS and the active window believe the key to be in, but is not necessarily the same as the physical state, that is, whether the user is physically holding it down.

Command:

KeyWait

ahkpy.get_caps_lock_state() bool[source]
ahkpy.get_num_lock_state() bool[source]
ahkpy.get_scroll_lock_state() bool[source]
ahkpy.get_insert_state() bool[source]

Retrieve the toggle state of CapsLock, NumLock, ScrollLock, and Insert keys.

Command:

GetKeyState

ahkpy.set_caps_lock_state(state: bool, always=False)[source]
ahkpy.set_num_lock_state(state: bool, always=False)[source]
ahkpy.set_scroll_lock_state(state: bool, always=False)[source]

Set the toggle state of CapsLock, NumLock, and ScrollLock keys.

If the optional always argument is True, forces the key to stay on or off.

Command:

SetCapsLockState / SetNumLockState / SetScrollLockState

Input Blocking

A couple of context managers to block user input:

with ahkpy.block_input():
    subprocess.Popen(["notepad"])
    ahkpy.windows.wait_active("Untitled - Notepad")
    ahkpy.send("{F5}")  # Pastes time and date

Use sparingly. Prefer the Input and Play send modes instead, because they buffer the user input while sending.

ahkpy.block_input()[source]

Block all user input unconditionally.

Command:

BlockInput

ahkpy.block_input_while_sending()[source]

Block user input while a send() is in progress.

This also blocks user input during mouse automation, because mouse clicks and movements are implemented using the send() function.

Command:

BlockInput, Send

ahkpy.block_mouse_move()[source]

Block the mouse cursor movement.

Command:

BlockInput, MouseMove

Settings

Settings modify the delay between execution of Window and Control methods; set the mode, level, delay and duration of the simulated key presses and mouse clicks, the speed of mouse movement.

Each thread has its own current settings which are accessed or changed using the get_settings() and set_settings() functions.

ahkpy.get_settings() ahkpy.Settings[source]

Return the current settings for the active thread.

ahkpy.set_settings(settings)[source]

Set the current settings for the active thread.

ahkpy.local_settings(settings=None)[source]

Return a context manager that will set the current settings for the active thread to a copy of settings on entry to the with-statement and restore the previous settings when exiting the with-statement. If no context is specified, a copy of the current settings is used.

For example, the following code removes the current delay between window manipulations, modifies the active window, and then automatically restores the previous settings:

prev_delay = ahkpy.get_settings().win_delay

with ahkpy.local_settings() as settings:
    settings.win_delay = 0
    win = ahkpy.windows.get_active()
    win.maximize()
    win.restore()

assert ahkpy.get_settings().win_delay == prev_delay

The function can also be used to safely change the settings of an AHK callback without affecting the settings in other functions:

@ahkpy.hotkey("F1")
def isolated_settings():
    settings = ahkpy.local_settings().activate()
    settings.win_delay = 0
    ...
ahkpy.default_settings

The default instance of Settings. It is set as the current settings at the start of the program. Changing individual settings here affects all yet-to-be-run AHK callbacks and Python threads.

class ahkpy.Settings[source]

The object that holds thread-local AutoHotkey settings. All delays and durations are in seconds.

control_delay: float = 0.02

The delay after each control-modifying method: check(), uncheck(), enable(), disable(), hide(), show(), focus(), paste(), choose_item_index(), choose_item(), move(), and the text, is_checked, list_choice_index, is_enabled, is_visible, rect, position, size, x, y, width, height setters.

Command:

SetControlDelay

key_delay: float = 0.01

The delay after each keystroke sent by send_event() and window.BaseWindow.send().

Command:

SetKeyDelay

key_duration: float = -1

The delay after the press of the key and before its release sent by send_event() and window.BaseWindow.send().

Command:

SetKeyDelay

key_delay_play: float = -1

The delay after each keystroke sent by send_play().

Command:

SetKeyDelay

key_duration_play: float = -1

The delay after the press of the key and before its release sent by send_play().

Command:

SetKeyDelay

mouse_delay: float = 0.01

The delay after each mouse movement or click in the Event mode.

Command:

SetMouseDelay

mouse_delay_play: float = -1

The delay after each mouse movement or click in the Play mode.

Command:

SetMouseDelay

mouse_speed: int = 2

The speed of mouse movement in the range 0 (fastest) to 100 (slowest). Affects only the Event mode.

Command:

SetDefaultMouseSpeed

send_level: int = 0

Controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings. Must be an integer between 0 and 100.

Command:

SendLevel

send_mode: str = 'input'

The default mode for send() and mouse functions.

Command:

SendMode

win_delay: float = 0.1

The delay after each window-modifying method. It affects the following:

Command:

SetWinDelay

Timers

ahkpy.set_timer(interval=0.25, func=None, *args, priority=0)[source]

Create a timer that will run func periodically with arguments args after interval seconds have passed.

If you want the func to be called with keyword arguments use functools.partial().

The optional priority argument sets the priority of the AHK thread where func will be executed. It must be an int between -2147483648 and 2147483647. Defaults to 0.

If func is given, returns an instance Timer. Otherwise, the function works as a decorator:

@ahkpy.set_timer(1)
def handler():
    print("tick")

assert isinstance(handler, ahkpy.Timer)
Command:

SetTimer

ahkpy.set_countdown(interval=0.25, func=None, *args, priority=0)[source]

Create a timer that will run func once with arguments args after interval seconds have passed.

If you want the func to be called with keyword arguments use functools.partial().

The optional priority argument sets the priority of the AHK thread where func will be executed. It must be an int between -2147483648 and 2147483647. Defaults to 0.

If func is given, returns an instance Timer. Otherwise, the function works as a decorator:

@ahkpy.set_countdown(1)
def handler():
    print("boom")

assert isinstance(handler, ahkpy.Timer)
Command:

SetTimer

class ahkpy.Timer(interval=0.25, func=None, priority=0, periodic=True)[source]

This object represents an action that should be run after a certain amount of time has passed.

Creating an instance of Timer doesn’t register the function in AHK. Use the set_timer() or set_countdown() functions instead.

start(interval=None, priority=None, periodic=None)[source]

Start a stopped timer or restart a running timer.

If the interval, priority, or periodic arguments are given, the Timer instance will be updated with the new values. See the Timer.update() method.

update(func=None, interval=None, priority=None, periodic=None, force_restart=False)[source]

Update the parameters of a timer and register them in AHK.

Passing any of func, interval, or periodic arguments restarts the timer. Passing only the priority argument updates the timer without restarting.

Note

Changing the attributes of the timer instance doesn’t affect the underlying AHK timer. Call the Timer.update() to actually apply the changes to the AHK timer:

t = ahkpy.set_timer(1, print, "beep")
t.interval = 0.5
# ^^ Does not change the frequency of prints!

t.update()  # Makes the timer fire twice a second.
stop()[source]

Stop the timer.

Windows

ahkpy.windows
ahkpy.visible_windows

The instances of Windows that match only visible windows.

ahkpy.all_windows

An instance of Windows that matches visible and hidden windows.

The following example shows how to get the window ID of the main AutoHotkey window:

import os
ahk_win = ahk.all_windows.first(pid=os.getpid())
class ahkpy.Windows[source]

The immutable object containing the criteria that is used to match the windows, iterate over them, do bulk actions, or to pick one window.

filter(title: str = UNSET, **criteria)[source]

Match specific windows using the given criteria. All strings are case-sensitive.

Parameters:
  • title (str) – the window title to match. The matching behavior is specified in the match argument and defaults to "startswith".

  • class_name (str) – the window class to match.

  • id (int) – the unique ID of a window or a control; also known as HWND.

  • pid (int) – the process identifier that is used to match the windows belonging to this process.

  • exe (str) – the filename of the process that is used to match the windows belonging to this process. If match is "regex", the exe argument accepts a regular expression that matches the full path of the process.

  • text (str) – the substring from a single text element of the target window. The matching behavior is affected by the include_hidden_text() and match_text_slow() methods.

  • match (str) –

    sets the matching behavior. Takes one of the following values:

    • "startswith" – a window’s title must start with the given title.

    • "contains" – a window’s title must contain the given title.

    • "exact" – a window’s title must exactly match the given title.

    • "regex" – changes title, class_name, exe, and text arguments to accept PCRE regular expressions.

    Defaults to "startswith".

exclude(title: str = UNSET, **exclude_criteria)[source]

Exclude windows from the match using the given criteria. All strings are case-sensitive.

Parameters:
  • title (str) – exclude windows with the given title.

  • text (str) – exclude windows with the given text. The matching behavior is affected by the match_text_slow() method only. It’s not affected by include_hidden_text().

  • match (str) – sets the matching behavior. For more information refer to filter().

include_hidden_windows(include=True)[source]

Change the window-matching behavior based on window visibility.

If include is true, includes the hidden windows in the search.

Default behavior is matching only visible windows while ignoring the hidden ones.

exclude_hidden_windows()[source]

Exclude hidden windows from the search.

A shorthand for windows.include_hidden_windows(False).

include_hidden_text(include=True)[source]

Change whether to ignore invisible controls when matching windows using the text criterion.

If include is false, ignores the invisible controls when searching for text in the windows.

Default behavior is searching for visible and hidden text.

exclude_hidden_text()[source]

Exclude hidden text from the search.

A shorthand for windows.include_hidden_text(False).

match_text_slow(is_slow=True)[source]

Change how windows are matched when using the text criterion.

If is_slow is true, the matching can be much slower, but works with all controls which respond to the WM_GETTEXT message.

Default behavior is to use the fast mode. However, certain types of controls are not detected. For instance, text is typically detected within Static and Button controls, but not Edit controls, unless they are owned by the script.

first(title: str = UNSET, **criteria) ahkpy.Window[source]

Return the window handle of the first (top) matching window.

If there are no matching windows, returns Window(None).

For arguments refer to filter().

Aliases:

exist(), top()

Command:

WinExist

last(title: str = UNSET, **criteria) ahkpy.Window[source]

Return the window handle of the last (bottom) matching window.

If there are no matching windows, returns Window(None).

For arguments refer to filter().

Alias:

bottom()

Command:

WinGet, $, IDLast

get_active(title: str = UNSET, **criteria) ahkpy.Window[source]

Return the window instance of the active matching window.

If no criteria are given, returns the current active window. If no window is active, returns Window(None).

For arguments refer to filter().

Command:

WinActive

wait(title: str = UNSET, *, timeout=None, **criteria) ahkpy.Window[source]

Wait until the specified window exists and return it.

Returns the first matched window. If there are no matching windows after timeout seconds, then Window(None) will be returned. If timeout is not specified or None, there is no limit to the wait time.

For other arguments refer to filter().

Command:

WinWait

wait_active(title: str = UNSET, *, timeout=None, **criteria) ahkpy.Window[source]

Wait until the window is active and return it.

For more information refer to wait().

Command:

WinWaitActive

wait_inactive(title: str = UNSET, *, timeout=None, **criteria) bool[source]

Wait until there are no matching active windows.

Returns True if there are no matching active windows. If there are still matching windows after timeout seconds, then False will be returned. If timeout is not specified or None, there is no limit to the wait time.

For other arguments refer to filter().

Command:

WinWaitNotActive

wait_close(title: str = UNSET, *, timeout=None, **criteria) bool[source]

Wait until there are no matching windows.

Returns True if there are no matching windows. If there are still matching windows after timeout seconds, then False will be returned. If timeout is not specified or None, there is no limit to the wait time.

For other arguments refer to filter().

Command:

WinWaitClose

close_all(title: str = UNSET, *, timeout=None, **criteria) bool[source]

Close all matching windows.

Returns True if all matching windows were closed. If there are still matching windows after timeout seconds, then False will be returned. If timeout is not specified or None, the function returns immediately.

For arguments refer to filter().

Command:

WinClose

hide_all(title: str = UNSET, **criteria)[source]

Hide all matching windows.

For arguments refer to filter().

Command:

WinHide

kill_all(title: str = UNSET, *, timeout=None, **criteria) bool[source]

Forces all matching windows to close.

Returns True if all matching windows were closed. If there are still matching windows after timeout seconds, then False will be returned. If timeout is not specified or None, the function returns immediately.

For arguments refer to filter().

Command:

WinKill

maximize_all(title: str = UNSET, **criteria)[source]

Maximize all matching windows.

For arguments refer to filter().

Command:

WinMaximize

minimize_all(title: str = UNSET, **criteria)[source]

Minimize all matching windows.

For arguments refer to filter().

Command:

WinMinimize

restore_all(title: str = UNSET, **criteria)[source]

Restore all matching windows.

For arguments refer to filter().

Command:

WinRestore

show_all(title: str = UNSET, **criteria)[source]

Show all matching windows.

For arguments refer to filter().

Command:

WinShow

window_context(title: str = UNSET, **criteria) ahkpy.HotkeyContext[source]

Create a context for hotkeys that will work only when the matching windows exist.

For arguments refer to filter().

Command:

Hotkey, IfWinExist, #IfWinExist.

nonexistent_window_context(title: str = UNSET, **criteria) ahkpy.HotkeyContext[source]

Create a context for hotkeys that will work only when there are no matching windows.

For arguments refer to filter().

Command:

Hotkey, IfWinNotExist, #IfWinNotExist.

active_window_context(title: str = UNSET, **criteria) ahkpy.HotkeyContext[source]

Create a context for hotkeys that will work only when the matching windows are active.

For arguments refer to filter().

Command:

Hotkey, IfWinActive, #IfWinActive.

inactive_window_context(title: str = UNSET, **criteria) ahkpy.HotkeyContext[source]

Create a context for hotkeys that will work only when the matching windows are not active.

For arguments refer to filter().

Command:

Hotkey, IfWinNotActive, #IfWinNotActive.

__iter__() Iterator[ahkpy.Window][source]

Return matching windows ordered from top to bottom.

Command:

WinGet, $, List

__len__()[source]

Return the number of matching windows.

Command:

WinGet, $, Count

class ahkpy.window.WindowHandle(id: int | None)[source]

The immutable object that contains the id (HWND) of a window/control.

__bool__()[source]

Check if the window/control exists.

Returns True if the window/control exists. Returns False if the window/control doesn’t exist or it’s a Window(None) or Control(None) instance.

property exists: bool

The window/control existence (read-only).

Returns True if the window/control exists. Returns False if the window/control doesn’t exist or it’s a Window(None) or Control(None) instance.

Command:

WinExist

class ahkpy.window.BaseWindow(id: int | None)[source]

Bases: WindowHandle

Base window class that is inherited by Window and Control classes.

To get a window instance, use first(), last(), get_active() methods, or iterate the windows with __iter__().

To get a control instance, use the get_control(), get_focused_control(), or get a list of window controls with controls.

property style: WindowStyle | None

The styles of the window/control.

Returns None unless the window exists.

Type:

WindowStyle

Command:

WinGet, $, Style, WinSet, $, Style, ControlGet, $, Style, Control, $, Style

property ex_style: ExWindowStyle | None

The extended styles of the window/control.

Returns None unless the window exists.

Type:

ExWindowStyle

Command:

WinGet, $, ExStyle, WinSet, $, ExStyle, ControlGet, $, ExStyle, Control, $, ExStyle

property class_name: str | None

The window/control class name (read-only).

Returns None unless the window exists.

Type:

str

Command:

WinGetClass

property pid: int | None

The identifier of the process that created the window/control (read-only).

Returns None unless the window exists.

Type:

int

Command:

WinGet, PID

property process_name: str | None

The name of the executable that created the window/control (read-only).

Returns None unless the window exists.

Type:

str

Alias:

exe

Command:

WinGet, ProcessName

property process_path: str | None

The full path to the executable that created the window/control (read-only).

Returns None unless the window exists.

Type:

str

Command:

WinGet, ProcessPath

property rect: Tuple[int, int, int, int] | None

The position and size of the window/control as a (x, y, width, height) tuple.

Returns None unless the window exists.

Type:

Tuple[int, int, int, int]

Command:

WinGetPos, ControlGetPos, WinMove, ControlMove

property position

The window/control position as a (x, y) tuple.

Returns None unless the window exists.

Type:

Tuple[int, int]

Command:

WinGetPos, ControlGetPos, WinMove, ControlMove

property x

The x coordinate of the window/control.

Returns None unless the window exists.

Type:

int

Command:

WinGetPos, ControlGetPos, WinMove, ControlMove

property y

The y coordinate of the window/control.

Returns None unless the window exists.

Type:

int

Command:

WinGetPos, ControlGetPos, WinMove, ControlMove

property size

The window/control size.

Returns a (width, height) tuple. If the window doesn’t exist, returns None.

Type:

Tuple[int, int]

Command:

WinGetPos, ControlGetPos, WinMove, ControlMove

property width

The window/control width.

Returns None unless the window exists.

Type:

int

Command:

WinGetPos, ControlGetPos, WinMove, ControlMove

property height

The window/control height.

Returns None unless the window exists.

Type:

int

Command:

WinGetPos, ControlGetPos, WinMove, ControlMove

move(x=None, y=None, width=None, height=None)[source]

Move and/or resize the window/control.

Does nothing unless the window/control exists.

Command:

WinMove, ControlMove

property is_enabled: bool | None

The enabled state of the window/control.

Returns None unless the window exists.

Type:

bool

Command:

WinSet, Enable, ControlGet, $, Enabled, Control, Enable

enable()[source]

Enable the window/control.

Does nothing unless the window/control exists.

Command:

WinSet, Enable, Control, Enable

disable()[source]

Disable the window/control.

Does nothing unless the window/control exists.

Command:

WinSet, Disable, Control, Disable

property is_visible

The visibility of the window/control.

Returns False unless the window/control exists.

Type:

bool

Command:

WinShow, ControlGet, $, Visible, Control, Show

show()[source]

Show the window/control.

Does nothing unless the window/control exists.

Command:

WinShow, Control, Show

hide()[source]

Hide the window/control.

Does nothing unless the window/control exists.

Command:

WinHide, Control, Hide

send(keys)[source]

Send simulated keystrokes to the window/control.

Unlike the send() function, mouse clicks cannot be sent.

Does nothing unless the window/control exists.

Command:

ControlSend

send_message(msg: int, w_param: int = 0, l_param: int = 0, signed_int=False, timeout=5) int | None[source]

Send a message to the window/control and get a response.

The msg argument is the message number to send. See the message list for common numbers. The w_param and l_param arguments are the first and second components of the message.

If there is no response after timeout seconds, then an Error will be raised. If timeout is not specified or None, there is no limit to the wait time.

The range of possible response values depends on the target window and the version of AutoHotkey that is running. When using the 32-bit version of AutoHotkey, or if the target window is 32-bit, the result is a 32-bit integer. When using the 64-bit version of AutoHotkey with a 64-bit window, the result is a 64-bit integer.

If signed_int argument is true, the response is interpreted as a signed integer. Defaults to False.

Returns None if the window/control doesn’t exist.

Command:

SendMessage

post_message(msg: int, w_param: int = 0, l_param: int = 0) bool | None[source]

Post a message to the window/control.

The msg argument is the message number to send. See the message list for common numbers. The w_param and l_param arguments are the first and second components of the message.

Returns True if the message was received. Returns False if there was a problem. Returns None if the window/control doesn’t exist.

Command:

PostMessage

class ahkpy.Window(id: int | None)[source]

Bases: BaseWindow

The object representing a window.

property is_active: bool

Whether the window is active (read-only).

Returns None unless the window exists.

Type:

bool

Command:

WinActive

property text: str | None

The text that was retrieved from the window (read-only).

Each text element ends with "\r\n". If the window doesn’t exist, returns None. Raises an Error if there was a problem retrieving the window text.

Type:

str

Command:

WinGetText

property title: str | None

The window title.

Returns None unless the window exists.

Type:

str

Command:

WinGetTitle, WinSetTitle

property is_minimized: bool | None

Whether the window is minimized.

Returns None unless the window exists.

Setting True minimizes the window, setting False restores the window if it’s minimized.

Type:

bool

Command:

WinGet, MinMax, WinMinimize, WinRestore

toggle_minimized()[source]

Toggle the minimized state of the window.

If window is minimized, restores it. Otherwise, minimizes it. Does nothing unless the window exists.

Command:

WinMinimize, WinRestore

minimize()[source]

Minimize the window.

Does nothing unless the window exists.

Command:

WinMinimize

property is_restored: bool | None

Whether the window is not minimized nor maximized (read-only).

Returns None unless the window exists.

Type:

bool

Command:

WinGet, MinMax

restore()[source]

Restore the window.

Does nothing unless the window exists.

Command:

WinRestore

property is_maximized: bool | None

Whether the window is maximized.

Returns None unless the window exists.

Setting True maximizes the window, setting False restores the window if it’s maximized.

Type:

bool

Command:

WinGet, MinMax, WinMaximize, WinRestore

toggle_maximized()[source]

Toggle the maximized state of the window.

If window is maximized, restores it. Otherwise, maximizes it. Does nothing unless the window exists.

Command:

WinMaximize, WinRestore

maximize()[source]

Maximize the window.

Does nothing unless the window exists.

Command:

WinMaximize

property control_classes: List[str] | None

The list of class names of the window controls (read-only).

Returns None unless the window exists.

Type:

List[str]

Command:

WinGet, ControlList

property controls: List[Control] | None

The list of window controls (read-only).

Returns None unless the window exists.

Type:

List[Control]

Command:

WinGet, ControlListHwnd

get_control(class_or_text, match='startswith') ahkpy.Control[source]

Find the window control by its class name or text.

In the case of searching the control by its text, the optional match argument specifies the matching behavior and defaults to "startswith". For other modes refer to Windows.filter().

Returns Control(None) if either window or control doesn’t exist.

Command:

ControlGet

get_focused_control() ahkpy.Control[source]

Get the currently focused control.

Returns Control(None) if the window doesn’t exist or no control is focused.

Command:

ControlGet

property always_on_top: bool | None

Whether the window is always on top.

Returns None unless the window exists.

Type:

bool

Command:

WinSet, AlwaysOnTop

pin_to_top()[source]

Make the window be always on top.

Does nothing unless the window exists.

Command:

WinSet, AlwaysOnTop, On

unpin_from_top()[source]

Unpin the window from the top.

Does nothing unless the window exists.

Command:

WinSet, AlwaysOnTop, Off

toggle_always_on_top()[source]

Toggle the topmost state of the window.

Does nothing unless the window exists.

Command:

WinSet, AlwaysOnTop, Toggle

send_to_bottom()[source]

Send the window to the bottom; that is, beneath all other windows.

Does nothing unless the window exists.

Command:

WinSet, Bottom

bring_to_top()[source]

Bring the window to the top without explicitly activating it.

However, the system default settings will probably cause it to activate in most cases. In addition, this method may have no effect due to the operating system’s protection against applications that try to steal focus from the user (it may depend on factors such as what type of window is currently active and what the user is currently doing). One possible work-around is to call toggle_always_on_top() twice in a row.

Does nothing unless the window exists.

Command:

WinSet, Top

redraw()[source]

Redraw the window.

This method attempts to update the appearance/contents of a window by informing the OS that the window’s rectangle needs to be redrawn. If this approach does not work for a particular window, try move(). If that does not work, try hide() in combination with show().

Does nothing unless the window exists.

Command:

WinSet, Redraw

set_region(options: str)[source]

Change the shape of a window to rectangle, ellipse, or polygon.

Does nothing unless the window exists.

Command:

WinSet, Region

reset_region()[source]

Restore the window to its original/default display area.

Does nothing unless the window exists.

Command:

WinSet, Region

property opacity: int | None

The window opacity level.

Returns a integer between 0 and 255, where 0 indicates an invisible window and 255 indicates an opaque window.

Returns None under the following circumstances:

  • the window doesn’t exist

  • the window has no transparency level

  • the OS is older than Windows XP

  • other conditions (caused by OS behavior) such as the window having been minimized, restored, and/or resized since it was made transparent

Setting None makes the window opaque. Does nothing unless the window exists.

Type:

int

Command:

WinGet, Transparent, WinSet, Transparent

property transparent_color: Tuple[int, int, int] | None

The color that is marked transparent in the window.

Returns a (red, green, blue) tuple. The color components are integers between 0 and 255.

Returns None under the following circumstances:

  • the window doesn’t exist

  • the window has no transparent color

  • the OS is older than Windows XP

  • other conditions (caused by OS behavior) such as the window having been minimized, restored, and/or resized since it was made transparent

Setting None makes the window opaque. Does nothing unless the window exists.

Type:

Tuple[int, int, int]

Command:

WinGet, TransColor, WinSet, TransColor

activate(timeout=None) bool[source]

Activate the window.

Returns True if the window was activated. If the window is not active after timeout seconds, then False will be returned. If timeout is not specified or None, the function returns immediately.

Does nothing unless the window exists.

Command:

WinActivate

close(timeout=None) bool[source]

Close the window.

Returns True if the window was closed. If the window still exists after timeout seconds, then False will be returned. If timeout is not specified or None, the function returns immediately.

Command:

WinClose

kill(timeout=None) bool[source]

Forces the window to close.

Returns True if the window was closed. If the window still exists after timeout seconds, then False will be returned. If timeout is not specified or None, the function returns immediately.

Command:

WinKill

wait_active(timeout=None) bool[source]

Wait until the window is active.

Returns True if the window is active. If it’s still not active after timeout seconds, then False will be returned. If timeout is not specified or None, there is no limit to the wait time.

Command:

WinWaitActive

wait_inactive(timeout=None) bool[source]

Wait until the window is inactive.

Returns True if the window is inactive or doesn’t exist. If it’s still active after timeout seconds, then False will be returned. If timeout is not specified or None, there is no limit to the wait time.

Command:

WinWaitNotActive

wait_hidden(timeout=None) bool[source]

Wait until the window is hidden.

Returns True if the window is hidden or doesn’t exist. If it’s still visible after timeout seconds, then False will be returned. If timeout is not specified or None, there is no limit to the wait time.

Command:

WinWaitClose

wait_close(timeout=None) bool[source]

Wait until the window is closed.

Returns True if the window doesn’t exist. If it still exists after timeout seconds, then False will be returned. If timeout is not specified or None, there is no limit to the wait time.

Command:

WinWaitClose

get_status_bar_text(part=0) str | None[source]

Get the status bar text from the window.

The part argument specifies which part of the bar to retrieve. Defaults to 0, which is usually the part that contains the text of interest.

Returns None if the window doesn’t exist or there’s no status bar. Raises an Error if there was a problem accessing the status bar.

Command:

StatusBarGetText

wait_status_bar(bar_text='', *, timeout=None, part=0, interval=0.05, match='startswith') bool | None[source]

Wait until the window’s status bar contains the specified bar_text string.

If the status bar doesn’t contain the specified string after timeout seconds, then False will be returned. If timeout is not specified or None, there is no limit to the wait time.

The part argument specifies which part of the bar to retrieve. Defaults to 0, which is usually the part that contains the text of interest.

The interval argument specifies how often the status bar should be checked. Defaults to 0.05 seconds.

The match argument specifies how bar_text is matched. Defaults to "startswith". For other modes refer to Windows.filter().

Returns None if the window doesn’t exist or there’s no status bar. Raises an Error if there was a problem accessing the status bar.

Command:

StatusBarWait

class ahkpy.Control(id: int | None)[source]

Bases: BaseWindow

The object representing a control: button, edit, checkbox, radio button, list box, combobox, list view.

property is_checked: bool | None

Whether the checkbox or radio button is checked.

Returns None if the control doesn’t exist.

Type:

bool

Command:

ControlGet, $, Checked, Control, Check

check()[source]

Check the checkbox or radio button.

Does nothing unless the control exists.

To improve reliability, a Settings.control_delay is done automatically after calling this method.

Command:

Control, Check

uncheck()[source]

Uncheck the checkbox or radio button.

Does nothing unless the control exists.

To improve reliability, a Settings.control_delay is done automatically after calling this method.

Command:

Control, Uncheck

property text: str | None

The text of the control.

Each text element ends with "\r\n". If the window doesn’t exist, returns None.

To improve reliability, a Settings.control_delay is done automatically after setting the text.

Type:

str

Command:

ControlGetText, ControlSetText

property is_focused: bool

Whether the control is focused (read-only).

Returns False if the control doesn’t exist.

Type:

bool

focus()[source]

Focus the control.

Does nothing unless the control exists.

To improve reliability, a Settings.control_delay is done automatically after calling this method.

Command:

ControlFocus

paste(text)[source]

Paste text at the caret/insert position in an Edit control.

Does not affect the contents of the clipboard. Does nothing unless the control exists.

To improve reliability, a Settings.control_delay is done automatically after calling this method.

Command:

Control, EditPaste

property line_count: int | None

The number of lines in an Edit control (read-only).

All Edit controls have at least 1 line, even if the control is empty. Returns None if the control doesn’t exist.

Type:

int

Command:

ControlGet, $, LineCount

property current_line_number: int | None

The line number in an Edit control where the caret resides (read-only).

The first line is 0. If there is text selected in the control, the result is set to the line number where the selection begins. Returns None if the control doesn’t exist.

Type:

int

Command:

ControlGet, $, CurrentLine

property current_column: int | None

The column number in an Edit control where the caret resides (read-only).

The first column is 0. If there is text selected in the control, the result is set to the column number where the selection begins. Returns None if the control doesn’t exist.

Type:

int

Command:

ControlGet, $, CurrentCol

get_line(lineno: int) str | None[source]

Retrieve the text of line lineno in an Edit control.

Line 0 is the first line. If the specified line number is out of range, an Error is raised. Returns None if the control doesn’t exist.

If the lineno argument is negative, the number is relative to the end.

Command:

ControlGet, $, Line

property current_line: str | None

The text of the line in an Edit control where the caret resides (read-only).

If there is text selected in the control, the result is set to the line number where the selection begins. Returns None if the control doesn’t exist.

property selected_text: str | None

The selected text in an Edit control (read-only).

If no text is selected, the result is an empty string. Certain types of controls, such as RichEdit20A, might not produce the correct text in some cases (e.g. Metapad). Returns None if the control doesn’t exist.

Command:

ControlGet, $, Selected

property list_choice: str | None

The name of the currently selected entry in a ListBox or ComboBox (read-only).

Returns None if the control doesn’t exist or no item is selected.

Type:

str

Command:

ControlGet, $, Choice

property list_choice_index: int | None

The index of the currently selected entry in a ListBox or ComboBox.

The first item is 0. Returns None if the control doesn’t exist. Returns -1 if no item is selected.

Type:

int

choose_item_index(index)[source]

Set the selection in a ListBox or ComboBox to be the index entry.

The first item is 0. If the index argument is negative, it’s relative to the end of the list.

Does nothing unless the control exists. Raises an Error if the index is out of range.

To improve reliability, a Settings.control_delay is done automatically after calling this method.

Command:

Control, Choose

choose_item(value)[source]

Set the selection (choice) in a ListBox or ComboBox to be the first entry whose leading part matches value.

Does nothing unless the control exists. Raises an Error if no item matches the value.

To improve reliability, a Settings.control_delay is done automatically after calling this method.

Command:

Control, ChooseString

list_item_index(value) int | None[source]

Retrieve the entry number of a ListBox or ComboBox that is a case insensitive match for value.

Returns None if the control doesn’t exist. Returns -1 if no item matches the value.

Command:

ControlGet, $, FindString

property list_items: list | None

The list of items from a ListView, ListBox, ComboBox, or DropDownList (read-only).

If the control is a ListBox, ComboBox, or DropDownList, returns a list of strings. If the control is a ListView, returns a list of lists: rows and columns.

Returns None if the control doesn’t exist. Raises an Error if there was a problem getting list items.

Command:

ControlGet, $, List

property selected_list_items: List[List[str]] | None

The selected (highlighted) rows in a ListView control (read-only).

Returns [] if no item is selected. Returns None if the control doesn’t exist or isn’t a ListView. Raises an Error if there was a problem getting list items.

Type:

List[List[str]]

Command:

ControlGet, $, List, Selected

property focused_list_item: List[str] | None

The focused row in a ListView control (read-only).

Returns None if the control doesn’t exist, isn’t a ListView, or no item is focused. Raises an Error if there was a problem getting list items.

Type:

List[str]

Command:

ControlGet, $, List, Focused

get_list_items(*, selected=False, focused=False, column: int = None) list | None[source]

Retrieve items from a ListView control.

Returns None if the control doesn’t exist or isn’t a ListView. Raises an Error if column is out of range or there was a problem getting list items.

Parameters:
  • selected – if true, returns only selected rows.

  • focused – if true, returns only the focused row.

  • column (int) – return rows with only the given column, indexed by its number. Supports negative indexing.

Command:

ControlGet, $, List

property list_item_count: int | None

The total number of rows in a ListBox, ComboBox, or ListView control (read-only).

Returns None if the control doesn’t exist.

Type:

int

property selected_list_item_count: int | None

The number of selected (highlighted) rows in a ListView control (read-only).

Returns None if the control doesn’t exist or isn’t a ListView. Raises an Error if there was a problem getting list items.

Type:

int

Command:

ControlGet, $, List, Count Selected

property focused_list_item_index: int | None

The row number of the focused row in a ListView control (read-only).

The first item is 0. Returns -1 if no item is focused. Returns None if the control doesn’t exist or isn’t a ListView. Raises an Error if there was a problem getting list items.

Type:

int

Command:

ControlGet, $, List, Count Focused

property list_view_column_count: int | None

The number of columns in a ListView control (read-only).

Returns -1 if the count cannot be determined. Returns None if the control doesn’t exist or isn’t a ListView. Raises an Error if there was a problem getting list items.

Type:

int

Command:

ControlGet, $, List, Count Col

class ahkpy.WindowStyle(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntFlag

The object that holds the window styles.

For more information on styles refer to Window Styles on Microsoft Docs.

class ahkpy.ExWindowStyle(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntFlag

The object that holds the extended window styles.

For more information on styles refer to Extended Window Styles on Microsoft Docs.