Why does FlaUI fail to find elements at times?

394 Views Asked by At

my code is below

IntPtr hwnd = FindWindow(null, "dingding");
GetWindowThreadProcessId(hwnd, out dingID);
var myapp = FlaUI.Core.Application.Attach(dingID);
var myautomation = new UIA3Automation());
var searchTextBox = dingdingWindow.FindFirstDescendant(cf => cf.ByName("search"))?.AsTextBox();

most time it works well but sometimes when it goes to "var serchTextBox........", the result is null and the hwnd is ok and dingID is ok and searchTextBox is spotted with inspect.exe. I have to relaunch my app, then everything goes fine.

I am just curious about that? Can somebody tell me why and how to modify the code?

1

There are 1 best solutions below

0
DevSolar On

Depending on the size of your application and the complexity of its initialization, the control might not be there the moment the statement is executed, but milliseconds later (when you look at it with FlaUInspect) it is.

When looking for controls, especially right after start or after invoking some menu item that calls up a dialog etc., give the UI a bit of time to catch up. Retry.WhileNull() allows this very conveniently.

var searchTextBox = Retry.WhileNull(
    () => dingdingWindow.FindFirstDescendant(cf => cf.ByName("search"),
    timeout: TimeSpan.FromSeconds(2),
    throwOnTimeout: true,
    timeoutMessage: "Could not find Search control")
    .Result;