It looks like your waittopuielem method returns void - did you mean to post something like this version, which returns a bool?
public static bool waittopuielm(string appname, int retries = 1000, int retrytimeout = 1000)
{
bool foundMatch = false;
for (int i = 1; i <= retries; i++)
{
if (findtopuielm(appname))
{
foundMatch = true;
break;
}
else
{
Console.WriteLine("No match found, sleeping...");
}
Thread.Sleep(retrytimeout);
}
return foundMatch;
}
Other than that, your code seems to work as expected for me.
One suggestion: In your findtopuielm method, change the TreeScope value in the desktop element search from TreeScope.Descendants to TreeScope.Children:
AutomationElement appElement = desktopelem.FindFirst(TreeScope.Children, condition);
TreeScope.Descendants is probably doing more recursive searching than you want - all children of the desktop element will be searched, as well as every child of those elements (i.e. buttons, edit controls, and so forth).
So, the chances of finding the wrong element when searching for a relatively common string are high, unless you combine your NameProperty PropertyCondition with other properties in an AndCondition to narrow your search.