Utilities
FlaUI ships a set of helpers alongside the element API: waiting and retrying, keyboard and mouse
input, the System.Drawing value types, screenshots, highlight overlays, and a few small tools.
FlaUI for Python ports all of them. This page shows each one next to its C# original.
Every Python snippet on this page runs
The snippets come from
examples/pytest/test_utilities.py
and examples/pytest/test_advanced.py,
which run against the bundled WPF app:
| Helper | Python | C# | Use it to... |
|---|---|---|---|
| Retry | flaui.core.tools.Retry |
FlaUI.Core.Tools.Retry |
poll until a condition holds |
| Wait | flaui.core.input.Wait |
FlaUI.Core.Input.Wait |
let input settle, wait for a window to respond |
| Keyboard | flaui.core.input.Keyboard |
FlaUI.Core.Input.Keyboard |
type text, send shortcuts |
| Mouse | flaui.core.input.Mouse |
FlaUI.Core.Input.Mouse |
move, click, scroll, drag the real cursor |
| Drawing types | flaui.lib.system.drawing |
System.Drawing |
points, sizes, rectangles, colours |
| Capturing | flaui.core.capturing |
FlaUI.Core.Capturing |
screenshots and screen recordings |
| Highlighting | draw_highlight, OverlayManager |
DrawHighlight, IOverlayManager |
see which element a locator found |
| Debug | flaui.core.debug |
FlaUI.Core.Debug |
dump an element, get an XPath to it |
| Tools | flaui.core.tools |
FlaUI.Core.Tools |
virtualized lists, MSAA text, system info |
| TypeCast | flaui.lib.collections.TypeCast |
n/a | convert values at the Python/.NET boundary |
Check the units
Retry timeouts and intervals are milliseconds (int). Wait timeouts are seconds (float).
C# uses TimeSpan for both. The units table lists every API.
Retry
Retry calls a function over and over until its condition holds or the timeout runs out. Pick the
method by what you're waiting for:
| You're waiting for... | Method | Returns |
|---|---|---|
an element lookup to stop raising ElementNotFound |
WhileException |
the element |
something to become true (is_enabled, a name change, ...) |
WhileFalse |
True / False |
| something to become false | WhileTrue |
True / False |
| a truthy value, which you then use | While |
the value |
a value that isn't None |
WhileNull |
the value, or None on timeout |
a value to go away (become None) |
WhileNotNull |
None, or the last value on timeout |
| a non-empty list | WhileEmpty |
the list |
from flaui.core.tools import Retry
# Keep trying while the lookup raises ElementNotFound; give up after 5 s.
button = Retry.WhileException(
lambda: window.find_first_descendant(cf.by_automation_id("InvokableButton")),
timeout=5000,
interval=100,
throw_on_timeout=True,
).as_button()
# Or wait for a predicate to become true.
ready = Retry.WhileFalse(lambda: button.is_enabled, timeout=2000)
var button = Retry.WhileNull(
() => window.FindFirstDescendant(cf.ByAutomationId("InvokableButton")),
timeout: TimeSpan.FromSeconds(5),
interval: TimeSpan.FromMilliseconds(100),
throwOnTimeout: true).Result.AsButton();
var ready = Retry.WhileFalse(() => button.IsEnabled, TimeSpan.FromSeconds(2)).Result;
How it differs from C#:
- Lookups raise instead of returning
null. In C#,FindFirst*returnsnull, so you poll withWhileNull. In Python it raisesElementNotFound, so poll withWhileException. The other methods only retry onValueError/AssertionError(and only withignore_exception=True); any other exception stops them straight away. - No
RetryResult. Python returns the value orbooldirectly, rather than.Result. - No separate check function. C#'s
Retry.While(method, checkMethod)tests a second callable; Python'sWhiletests the method's own return value for truthiness. throw_on_timeoutbehaves differently depending on the method:WhileFalse/WhileTrue/WhileNull/WhileNotNullreturn quietly on timeout unless it is set, whileWhile,WhileNotandWhileEmptyalways raise unless you give themlast_value_on_timeoutordefault_on_timeout. Each method's API reference spells this out.
For assertions that wait, expect(...) reads better than
wrapping Retry in an assert.
Wait
until_input_is_processed()pauses briefly (100 ms by default) so queued input can land. Thepost_wait=Trueargument on input methods does the same thing.until_responsive(element)waits until the element's window accepts input again, for example after a long-running click.until_responsive_hwnd(handle)does the same from a window handle.while_cursor_is_busy()waits while the mouse cursor shows the busy or "working in background" shape. It's useful after an action that triggers a load with no UI you can poll.
Keyboard
Keyboard.type sends real key presses to whichever control has focus. Hold modifier keys with
Keyboard.pressing, which returns a context manager that releases the keys when the block ends,
even if it raises:
from flaui.core.input import Keyboard, Wait
from flaui.core.windows_api import VirtualKeyShort
text_box.focus()
with Keyboard.pressing([VirtualKeyShort.CONTROL]): # held down inside the block...
Keyboard.type_key(VirtualKeyShort.KEY_A) # ...so this is Ctrl+A (select all)
Keyboard.type("replaced") # types over the selection
Keyboard.type_key(VirtualKeyShort.TAB) # single keys by name
Wait.until_input_is_processed()
Other methods: type_simultaneously([...]) presses several keys together, press / release
give manual control, and type_scan_code / type_virtual_key_code send raw codes. Key names are on
flaui.core.windows_api.VirtualKeyShort.
Prefer patterns over keystrokes
Real keystrokes go to whatever has focus, and anything else happening on the desktop can get
mixed in. Setting text_box.text = ... uses the Value pattern and sends no keys at all. Use the
keyboard when the app needs real key events: shortcuts, key-driven navigation, or input
validation that only runs on typing.
Mouse
Also available: right_click, double_click, drag(start, end), drag_horizontally /
drag_vertically, and horizontal_scroll. Every method accepts post_wait. Movement speed is set
by Mouse.move_pixels_per_millisecond (see Configuration).
element.click() combines finding the clickable point and clicking it.
Drawing types
Screen geometry and colours use the System.Drawing types, wrapped as pydantic models.
bounding_rectangle returns a Rectangle, get_clickable_point() returns a Point, and so on.
Build your own from Python values with raw_value=:
from flaui.lib.system.drawing import Color, Point, Rectangle, Size
bounds = window.bounding_rectangle # Rectangle, in screen pixels
print(bounds.left, bounds.top, bounds.width, bounds.height)
middle = bounds.center() # Point
p = Point(raw_value=(10, 20)) # build your own from Python values...
moved = p + Size(raw_value=(5, 5)) # ...and combine them like the C# operators
box = Rectangle(raw_value=[0, 0, 100, 50]) # x, y, width, height
inside = box.contains(Point(raw_value=(10, 10)))
blue = Color.from_name("Blue") # or Color.Red, Color.from_argb(...)
Each wrapper exposes .raw_value (or .cs_object for colours) when you need to hand the real
.NET value to FlaUI yourself.
Screenshots and video
from flaui.core.capturing import Capture, CaptureSettings
with Capture.element(window) as image: # the image is disposed when the block ends
image.to_file(str(tmp_path / "window.png"))
with Capture.main_screen(CaptureSettings(output_scale=0.5)) as screen: # half size
screen.to_file(str(tmp_path / "screen.png"))
window.capture_to_file(str(tmp_path / "shortcut.png")) # one-liner on any element
Capture can also grab a single screen (screen(index)), any rectangle (rectangle(bounds)), or
every screen an element spans (screens_with_element). image.apply_overlays(MouseOverlay(image),
InfoOverlay(image)) draws the cursor and an info bar (time, machine name, CPU/RAM) onto a capture.
To record video, use VideoRecorder. It needs ffmpeg, which VideoRecorder.download_ffmpeg(folder)
can fetch for you. See the Capturing reference for overlays, typed settings and
recording examples.
Screenshot every failure automatically
Taking the screenshot from a test-framework hook means every failure gets one without any changes to the tests themselves. See Test design tips.
Highlighting elements
When you're not sure which element a locator found, draw a frame around it:
show() returns straight away; show_blocking() waits until the frame has disappeared. Durations
are in milliseconds.
Debugging elements
flaui.core.debug wraps FlaUI.Core.Debug. details() dumps an element's properties and
supported patterns (and those of its children) as text, which is useful in a failure message or a
log. get_xpath_to_element() turns an element you already found into an XPath locator. Both are
also methods on every element.
from flaui.core import debug
print(debug.details(button)) # or button.details(): AutomationId, ControlType, Name, patterns
desktop = automation.automation_base.get_desktop()
xpath = button.get_xpath_to_element(desktop) # e.g. "/Tab/TabItem[1]/Button[2]"
same_button = window.find_first_by_x_path(xpath) # the path is relative to the window
How the root changes the path:
| Call | Example result | Search it from |
|---|---|---|
get_xpath_to_element(element) |
/Window[1]/Tab/TabItem[1]/Button[2] |
the desktop |
get_xpath_to_element(element, desktop) |
/Tab/TabItem[1]/Button[2] |
the top-level window |
get_xpath_to_element(element, window) |
/TabItem[1]/Button[2] |
the window's Tab child |
A root leaves out the step for its direct child
Like FlaUI C#, passing root_element drops the step for the root's direct child. Pass the
desktop to get a path you can hand to window.find_first_by_x_path(). Without a root, FlaUI
indexes the window among every top-level window, which is slower on a busy desktop and depends
on what else is open, so prefer the desktop-rooted form for locators.
details() can return an empty string
FlaUI returns "" when it cannot read one of the properties it dumps. This happens now and then
on WinForms, where the MSAA proxy rejects a cached HelpText or AutomationId. FlaUI's error
text is logged as a warning on the flaui.core.debug logger.
Other tools
Virtualized lists (ItemRealizer)
Large WPF lists and grids only create UI Automation elements for the rows on screen. Realize them before searching through all of them:
System information (SystemInfo)
CPU and memory figures, useful to log next to a slow or flaky test. The Python version uses psutil instead of Windows performance counters.
MSAA role and state text (AccessibilityTextResolver)
from flaui.core.tools import AccessibilityTextResolver
legacy = window.raw_element.Patterns.LegacyIAccessible.Pattern # MSAA view of the element
role = AccessibilityTextResolver.get_role_text(legacy.Role.Value) # e.g. "window"
state = AccessibilityTextResolver.get_state_text(legacy.State.Value) # e.g. "focusable"
Also in flaui.core.tools
WindowsStoreAppLauncher.launch(aumid)starts a Store app and returns its process id.automation.application.launch_store_app(aumid)wraps it, as the Calculator gallery script shows.LocalizedStringsgives the scroll-bar names FlaUI uses for the current Windows language.
Converting values (TypeCast)
Most of the API converts values for you. When you call FlaUI directly through .raw_element, these
helpers convert at the boundary:
from flaui.lib.collections import TypeCast
span = TypeCast.cs_timespan(1500) # Python milliseconds -> System.TimeSpan
items = TypeCast.py_list(span.ToString().split(":")) # any C# IEnumerable -> Python list
TypeCast also has py_dict (a C# dictionary to a Python dict) and cs_datetime (a Python
date to System.DateTime, e.g. to set a DateTimePicker).