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.
wait_clipboard
(timeout: Optional[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
-
ahkpy.
on_clipboard_change
(func: Optional[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
-
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 theon_clipboard_change()
function instead.
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
-
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.
restart
()[source]¶ Terminate the currently running instance of the script and start a new one.
- Command
-
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
-
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 handleKeyboardInterrupt
: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.
GUI¶
Message Boxes¶
-
ahkpy.
message_box
(text=None, title=None, *, buttons='ok', icon=None, default_button=1, options=[], timeout=None) → Optional[str][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.
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
-
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
-
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
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 calltooltip.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
-
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
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
-
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 theon_message()
function instead.
Keyboard and Mouse¶
Hotkeys and Hotstrings¶
-
class
ahkpy.
HotkeyContext
(active_when: Optional[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 returnsTrue
.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
(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
-
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: Union[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 ofstr
, 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 tosend()
.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 tosend()
.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 toTrue
, 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
-
ahkpy.
default_context
¶ The default instance of
HotkeyContext
.
-
ahkpy.
remap_key
(...)[source]¶ Useful aliases for
default_context.hotkey()
,default_context.hotstring()
, anddefault_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 theHotkeyContext.hotkey()
method instead.-
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 theHotkeyContext.remap_key()
method instead.
-
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 theHotkeyContext.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)
-
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
-
ahkpy.
get_hotstring_end_chars
()[source]¶ Retrieve the set of end chars.
The default end chars are the following:
-()[]{}':;"/\,.?!\n \t
.- Command
-
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
-
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
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
mode (str) – the mode that is used to send keys and clicks. Takes one of the following values:
"input"
,"event"
,"play"
. Defaults to one currently set inSettings.send_mode
. If any of key_delay, key_duration, or mouse_delay arguments are given, and the current mode is Input, then reverts to the Event mode. For differences between the modes refer to Send variants.level (int) – controls which artificial keyboard and mouse events are ignored by hotkeys and hotstrings. It must be an integer between 0 and 100. Has no effect in the Play mode. Defaults to one currently set in
Settings.send_level
. For more information refer to SendLevel Remarks.key_delay (float) – the delay in seconds after each keystroke. Defaults to one currently set in
Settings.key_delay
orSettings.key_delay_play
. For more information refer to SetKeyDelay Remarks.key_duration (float) – the delay in seconds after pressing the key and before releasing it. Defaults to one currently set in
Settings.key_duration
orSettings.key_duration_play
. For more information refer to SetKeyDelay Remarks.mouse_delay (float) – the delay after each mouse movement or click. Defaults to one currently set in
Settings.mouse_delay
orSettings.mouse_delay_play
. For more information refer to SetMouseDelay Remarks.
- Command
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 toTrue
.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
-
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
-
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
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
-
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, returnsWindow(None)
. The window does not have to be active to be detected.- Command
-
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, returnsControl(None)
. The window does not have to be active for the control to be detected.- Command
-
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
-
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
-
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
-
ahkpy.
get_key_vk
(key_name: str) → int[source]¶ Return the virtual key code of a key.
>>> ahkpy.get_key_vk("F1") 112
- Command
-
ahkpy.
get_key_sc
(key_name: str) → int[source]¶ Return the scan code of a key.
>>> ahkpy.get_key_sc("F1") 59
- Command
-
ahkpy.
is_key_pressed
(key_name: str) → bool[source]¶ Return whether the key is pressed down physically.
- Command
-
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
-
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, thenFalse
will be returned. If timeout is not specified orNone
, 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
-
ahkpy.
get_insert_state
() → bool[source]¶ Retrieve the toggle state of CapsLock, NumLock, ScrollLock, and Insert keys.
- Command
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_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
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.
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 thetext
,is_checked
,list_choice_index
,is_enabled
,is_visible
,rect
,position
,size
,x
,y
,width
,height
setters.- Command
-
key_delay
: float = 0.01¶ The delay after each keystroke sent by
send_event()
andwindow.BaseWindow.send()
.- Command
-
key_duration
: float = -1¶ The delay after the press of the key and before its release sent by
send_event()
andwindow.BaseWindow.send()
.- Command
-
key_delay_play
: float = -1¶ The delay after each keystroke sent by
send_play()
.- Command
-
key_duration_play
: float = -1¶ The delay after the press of the key and before its release sent by
send_play()
.- Command
-
mouse_delay_play
: float = -1¶ The delay after each mouse movement or click in the Play mode.
- Command
-
mouse_speed
: int = 2¶ The speed of mouse movement in the range 0 (fastest) to 100 (slowest). Affects only the Event mode.
- Command
-
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
-
win_delay
: float = 0.1¶ The delay after each window-modifying method. It affects the following:
Windows
methods:close_all()
,hide_all()
,kill_all()
,maximize_all()
,minimize_all()
,restore_all()
,show_all()
Window
methods:minimize()
,restore()
,maximize()
,hide()
,show()
,close()
,kill()
,move()
Window
setters:is_maximized
,is_minimized
,is_enabled
,is_visible
,rect
,position
,size
,x
,y
,width
,height
- Command
-
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
-
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
-
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 theset_timer()
orset_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 theTimer.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.
-
Windows¶
-
ahkpy.
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()
andmatch_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 byinclude_hidden_text()
.match (str) – sets the matching behavior. For more information refer to
filter()
.
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 from the search.
A shorthand for
windows.include_hidden_windows(False)
.
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 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
-
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
-
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
-
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 orNone
, there is no limit to the wait time.For other arguments refer to
filter()
.- Command
-
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
-
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, thenFalse
will be returned. If timeout is not specified orNone
, there is no limit to the wait time.For other arguments refer to
filter()
.- Command
-
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, thenFalse
will be returned. If timeout is not specified orNone
, there is no limit to the wait time.For other arguments refer to
filter()
.- Command
-
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, thenFalse
will be returned. If timeout is not specified orNone
, the function returns immediately.For arguments refer to
filter()
.- Command
-
hide_all
(title: str = UNSET, **criteria)[source]¶ Hide all matching windows.
For arguments refer to
filter()
.- Command
-
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, thenFalse
will be returned. If timeout is not specified orNone
, the function returns immediately.For arguments refer to
filter()
.- Command
-
maximize_all
(title: str = UNSET, **criteria)[source]¶ Maximize all matching windows.
For arguments refer to
filter()
.- Command
-
minimize_all
(title: str = UNSET, **criteria)[source]¶ Minimize all matching windows.
For arguments refer to
filter()
.- Command
-
restore_all
(title: str = UNSET, **criteria)[source]¶ Restore all matching windows.
For arguments refer to
filter()
.- Command
-
show_all
(title: str = UNSET, **criteria)[source]¶ Show all matching windows.
For arguments refer to
filter()
.- Command
-
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
-
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
-
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
-
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
-
__iter__
() → typing.Iterator[ahkpy.Window][source]¶ Return matching windows ordered from top to bottom.
- Command
-
-
class
ahkpy.window.
WindowHandle
(id: Optional[int])[source]¶ The immutable object that contains the id (HWND) of a window/control.
-
class
ahkpy.window.
BaseWindow
(id: Optional[int])[source]¶ Bases:
ahkpy.window.WindowHandle
Base window class that is inherited by
Window
andControl
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 withcontrols
.-
property
style
¶ The styles of the window/control.
Returns
None
unless the window exists.- Type
- Command
WinGet, $, Style, WinSet, $, Style, ControlGet, $, Style, Control, $, Style
-
property
ex_style
¶ The extended styles of the window/control.
Returns
None
unless the window exists.
-
property
class_name
¶ The window/control class name (read-only).
Returns
None
unless the window exists.- Type
- Command
-
property
pid
¶ The identifier of the process that created the window/control (read-only).
Returns
None
unless the window exists.- Type
- Command
-
property
process_name
¶ The name of the executable that created the window/control (read-only).
Returns
None
unless the window exists.- Type
- Alias
exe
- Command
-
property
process_path
¶ The full path to the executable that created the window/control (read-only).
Returns
None
unless the window exists.- Type
- Command
-
property
rect
¶ The position and size of the window/control as a
(x, y, width, height)
tuple.Returns
None
unless the window exists.- Type
- Command
-
property
position
¶ The window/control position as a
(x, y)
tuple.Returns
None
unless the window exists.- Type
- Command
-
property
x
¶ The x coordinate of the window/control.
Returns
None
unless the window exists.- Type
- Command
-
property
y
¶ The y coordinate of the window/control.
Returns
None
unless the window exists.- Type
- Command
-
property
size
¶ The window/control size.
Returns a
(width, height)
tuple. If the window doesn’t exist, returnsNone
.- Type
- Command
-
property
width
¶ The window/control width.
Returns
None
unless the window exists.- Type
- Command
-
property
height
¶ The window/control height.
Returns
None
unless the window exists.- Type
- Command
-
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
-
property
is_enabled
¶ The enabled state of the window/control.
Returns
None
unless the window exists.- Type
- Command
-
disable
()[source]¶ Disable the window/control.
Does nothing unless the window/control exists.
- Command
-
property
is_visible
¶ The visibility of the window/control.
Returns
False
unless the window/control exists.- Type
- Command
-
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
-
send_message
(msg: int, w_param: int = 0, l_param: int = 0, signed_int=False, timeout=5) → Optional[int][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 timeoutNone
, 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
-
post_message
(msg: int, w_param: int = 0, l_param: int = 0) → Optional[bool][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. ReturnsFalse
if there was a problem. ReturnsNone
if the window/control doesn’t exist.- Command
-
property
-
class
ahkpy.
Window
(id: Optional[int])[source]¶ Bases:
ahkpy.window.BaseWindow
The object representing a window.
-
property
is_active
¶ Whether the window is active (read-only).
Returns
None
unless the window exists.
-
property
text
¶ The text that was retrieved from the window (read-only).
Each text element ends with
"\r\n"
. If the window doesn’t exist, returnsNone
. Raises anError
if there was a problem retrieving the window text.- Type
- Command
-
property
title
¶ The window title.
Returns
None
unless the window exists.- Type
- Command
-
property
is_minimized
¶ Whether the window is minimized.
Returns
None
unless the window exists.Setting
True
minimizes the window, settingFalse
restores the window if it’s minimized.- Type
- Command
-
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
-
property
is_restored
¶ Whether the window is not minimized nor maximized (read-only).
Returns
None
unless the window exists.- Type
- Command
-
property
is_maximized
¶ Whether the window is maximized.
Returns
None
unless the window exists.Setting
True
maximizes the window, settingFalse
restores the window if it’s maximized.- Type
- Command
-
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
-
property
control_classes
¶ The list of class names of the window controls (read-only).
Returns
None
unless the window exists.- Type
List[str]
- Command
-
property
controls
¶ The list of window controls (read-only).
Returns
None
unless the window exists.- Type
List[Control]
- Command
-
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 toWindows.filter()
.Returns
Control(None)
if either window or control doesn’t exist.- Command
-
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
-
property
always_on_top
¶ Whether the window is always on top.
Returns
None
unless the window exists.- Type
- Command
-
pin_to_top
()[source]¶ Make the window be always on top.
Does nothing unless the window exists.
- Command
-
unpin_from_top
()[source]¶ Unpin the window from the top.
Does nothing unless the window exists.
- Command
-
toggle_always_on_top
()[source]¶ Toggle the topmost state of the window.
Does nothing unless the window exists.
- Command
-
send_to_bottom
()[source]¶ Send the window to the bottom; that is, beneath all other windows.
Does nothing unless the window exists.
- Command
-
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
-
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, tryhide()
in combination withshow()
.Does nothing unless the window exists.
- Command
-
set_region
(options: str)[source]¶ Change the shape of a window to rectangle, ellipse, or polygon.
Does nothing unless the window exists.
- Command
-
reset_region
()[source]¶ Restore the window to its original/default display area.
Does nothing unless the window exists.
- Command
-
property
opacity
¶ 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
- Command
-
property
transparent_color
¶ 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
- Command
-
activate
(timeout=None) → bool[source]¶ Activate the window.
Returns
True
if the window was activated. If the window is not active after timeout seconds, thenFalse
will be returned. If timeout is not specified orNone
, the function returns immediately.Does nothing unless the window exists.
- Command
-
close
(timeout=None) → bool[source]¶ Close the window.
Returns
True
if the window was closed. If the window still exists after timeout seconds, thenFalse
will be returned. If timeout is not specified orNone
, the function returns immediately.- Command
-
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, thenFalse
will be returned. If timeout is not specified orNone
, the function returns immediately.- Command
-
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, thenFalse
will be returned. If timeout is not specified orNone
, there is no limit to the wait time.- Command
-
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, thenFalse
will be returned. If timeout is not specified orNone
, there is no limit to the wait time.- Command
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, thenFalse
will be returned. If timeout is not specified orNone
, there is no limit to the wait time.- Command
-
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, thenFalse
will be returned. If timeout is not specified orNone
, there is no limit to the wait time.- Command
-
get_status_bar_text
(part=0) → Optional[str][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 anError
if there was a problem accessing the status bar.- Command
-
wait_status_bar
(bar_text='', *, timeout=None, part=0, interval=0.05, match='startswith') → Optional[bool][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 orNone
, 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 toWindows.filter()
.Returns
None
if the window doesn’t exist or there’s no status bar. Raises anError
if there was a problem accessing the status bar.- Command
-
property
-
class
ahkpy.
Control
(id: Optional[int])[source]¶ Bases:
ahkpy.window.BaseWindow
The object representing a control: button, edit, checkbox, radio button, list box, combobox, list view.
-
property
is_checked
¶ Whether the checkbox or radio button is checked.
Returns
None
if the control doesn’t exist.- Type
- Command
-
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
-
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
-
property
text
¶ The text of the control.
Each text element ends with
"\r\n"
. If the window doesn’t exist, returnsNone
.To improve reliability, a
Settings.control_delay
is done automatically after setting the text.- Type
- Command
-
property
is_focused
¶ Whether the control is focused (read-only).
Returns
False
if the control doesn’t exist.- Type
-
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
-
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
-
property
line_count
¶ 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
- Command
-
property
current_line_number
¶ 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
- Command
-
property
current_column
¶ 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
- Command
-
get_line
(lineno: int) → Optional[str][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. ReturnsNone
if the control doesn’t exist.If the lineno argument is negative, the number is relative to the end.
- Command
-
property
current_line
¶ 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
¶ 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
-
property
list_choice
¶ 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
- Command
-
property
list_choice_index
¶ 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
-
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
-
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
-
list_item_index
(value) → Optional[int][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
-
property
list_items
¶ 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 anError
if there was a problem getting list items.- Command
-
property
selected_list_items
¶ The selected (highlighted) rows in a ListView control (read-only).
Returns
[]
if no item is selected. ReturnsNone
if the control doesn’t exist or isn’t a ListView. Raises anError
if there was a problem getting list items.- Type
List[List[str]]
- Command
-
property
focused_list_item
¶ 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 anError
if there was a problem getting list items.- Type
List[str]
- Command
-
get_list_items
(*, selected=False, focused=False, column: Optional[int] = None) → Optional[list][source]¶ Retrieve items from a ListView control.
Returns
None
if the control doesn’t exist or isn’t a ListView. Raises anError
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
-
property
list_item_count
¶ The total number of rows in a ListBox, ComboBox, or ListView control (read-only).
Returns
None
if the control doesn’t exist.- Type
-
property
selected_list_item_count
¶ 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 anError
if there was a problem getting list items.- Type
- Command
-
property
focused_list_item_index
¶ 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 anError
if there was a problem getting list items.- Type
- Command
-
property
-
class
ahkpy.
WindowStyle
(value)[source]¶ Bases:
enum.IntFlag
The object that holds the window styles.
For more information on styles refer to Window Styles on Microsoft Docs.
-
class
ahkpy.
ExWindowStyle
(value)[source]¶ Bases:
enum.IntFlag
The object that holds the extended window styles.
For more information on styles refer to Extended Window Styles on Microsoft Docs.