Skip to content

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:

uv run pytest examples/pytest/test_utilities.py -v
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* returns null, so you poll with WhileNull. In Python it raises ElementNotFound, so poll with WhileException. The other methods only retry on ValueError / AssertionError (and only with ignore_exception=True); any other exception stops them straight away.
  • No RetryResult. Python returns the value or bool directly, rather than .Result.
  • No separate check function. C#'s Retry.While(method, checkMethod) tests a second callable; Python's While tests the method's own return value for truthiness.
  • throw_on_timeout behaves differently depending on the method: WhileFalse / WhileTrue / WhileNull / WhileNotNull return quietly on timeout unless it is set, while While, WhileNot and WhileEmpty always raise unless you give them last_value_on_timeout or default_on_timeout. Each method's API reference spells this out.

For assertions that wait, expect(...) reads better than wrapping Retry in an assert.

Wait

from flaui.core.input import Wait

Wait.until_input_is_processed()  # let queued mouse/keyboard input settle
Wait.until_responsive(window, timeout_in_secs=5)  # the window's UI thread accepts input
busy_cleared = Wait.while_cursor_is_busy(timeout_in_secs=10)  # no spinning/hourglass cursor
Wait.UntilInputIsProcessed();
Wait.UntilResponsive(window, TimeSpan.FromSeconds(5));
// No C# equivalent of while_cursor_is_busy: it is a Python addition.
  • until_input_is_processed() pauses briefly (100 ms by default) so queued input can land. The post_wait=True argument 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()
textBox.Focus();
using (Keyboard.Pressing(VirtualKeyShort.CONTROL))
{
    Keyboard.Type(VirtualKeyShort.KEY_A);
}
Keyboard.Type("replaced");
Keyboard.Type(VirtualKeyShort.TAB);
Wait.UntilInputIsProcessed();

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

from flaui.core.input import Mouse

point = text_box.get_clickable_point()  # a screen Point inside the element
Mouse.move_to(new_position=point)
print(Mouse.position)  # Point(x=..., y=...)
Mouse.click(point, post_wait=True)
Mouse.scroll(-2)  # negative scrolls down
var point = textBox.GetClickablePoint();
Mouse.MoveTo(point);
Console.WriteLine(Mouse.Position);
Mouse.Click(point);
Wait.UntilInputIsProcessed();
Mouse.Scroll(-2);

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(...)
var bounds = window.BoundingRectangle;
var middle = bounds.Center();

var p = new Point(10, 20);
var moved = p + new Size(5, 5);
var box = new Rectangle(0, 0, 100, 50);
var inside = box.Contains(new Point(10, 10));

var blue = Color.FromName("Blue");

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
using (var image = Capture.Element(window))
{
    image.ToFile(@"C:\temp\window.png");
}
using (var screen = Capture.MainScreen(new CaptureSettings { OutputScale = 0.5 }))
{
    screen.ToFile(@"C:\temp\screen.png");
}
window.CaptureToFile(@"C:\temp\shortcut.png");

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:

from flaui.lib.system.drawing import Color

button.draw_highlight(Color.Blue, duration=500)  # frame the element for 0.5 s

overlay = automation.automation_base.overlay_manager  # or any rectangle on screen
overlay.show(window.bounding_rectangle, Color.Red, duration_in_ms=500)
button.DrawHighlight(false, Color.Blue, TimeSpan.FromMilliseconds(500));

automation.OverlayManager.Show(window.BoundingRectangle, Color.Red, 500);

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
Console.WriteLine(Debug.Details(button));

var desktop = automation.GetDesktop();
var xpath = Debug.GetXPathToElement(button, desktop);
var sameButton = window.FindFirstByXPath(xpath);

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:

from flaui.core.tools import ItemRealizer

large_list = window.find_first_descendant(cf.by_automation_id("LargeListView"))
ItemRealizer.realize_items(large_list)  # scrolls through and realizes each item
var largeList = window.FindFirstDescendant(cf.ByAutomationId("LargeListView"));
ItemRealizer.RealizeItems(largeList);

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.

from flaui.core.tools import SystemInfo

print(f"CPU {SystemInfo.cpu_usage()}%  RAM {SystemInfo.physical_memory_used_percent()}% used")
free_gb = SystemInfo.physical_memory_free() / 1024**3
Console.WriteLine($"CPU {SystemInfo.CpuUsage}%  RAM {SystemInfo.PhysicalMemoryUsedPercent}% used");

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"
var legacy = window.Patterns.LegacyIAccessible.Pattern;
var role = AccessibilityTextResolver.GetRoleText(legacy.Role.Value);
var state = AccessibilityTextResolver.GetStateText(legacy.State.Value);

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.
  • LocalizedStrings gives 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).