Datagrid contents with UI Automation and .net

2020-07-10 09:40发布

问题:

I'm having some trouble reading the contents of a Datagrid in an external application using UI Automation and could use some pointers. Here's what I have so far:

int id = System.Diagnostics.Process.GetProcessesByName("Book")[0].Id;
AutomationElement desktop = AutomationElement.RootElement;

AutomationElement bw = desktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ProcessIdProperty, id));

AutomationElement datagrid = bw.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "lv"));

AutomationElementCollection lines = datagrid.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem));

AutomationElementCollection items = lines[1].FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom));

GridItemPattern pattern = items[1].GetCurrentPattern(GridItemPattern.Pattern) as GridItemPattern;
TableItemPattern tablePattern = items[1].GetCurrentPattern(TableItemPattern.Pattern) as TableItemPattern;

This works in as much as I can access the column ids and row ids from the GridItemPattern and TableItemPattern but how do I access the value that is in that specific cell? Is it even possible?

Thanks.

回答1:

I think you need to use ValuePattern for it. Just like that:

ValuePattern pattern = items[0].GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
string value = pattern.Current.Value;


回答2:

I finally figured this out, it requires the use of CacheRequest to request the Name property on the AutomationElement. Here's the final code:

var cacheRequest = new CacheRequest
{
    AutomationElementMode = AutomationElementMode.None,
    TreeFilter = Automation.RawViewCondition
};

cacheRequest.Add(AutomationElement.NameProperty);
cacheRequest.Add(AutomationElement.AutomationIdProperty);

cacheRequest.Push();

var targetText = loginLinesDetails[i].FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "TextBlock"));

cacheRequest.Pop();

var myString = targetText.Cached.Name;


回答3:

I am not familiar with the AutomationElement classes but I have used AutoIT to automate some simple windows stuff in the past (find a dialog, click a button, etc) and it was cake. You might consider it. The download contains a .dll you can reference from a .Net solution.

I'm not sure if the external app is a WinForm grid or not but here is an ASP.Net grid example: http://www.autoitscript.com/forum/topic/13709-how-to-get-the-contents-of-datagrid-control/

Then again, if you are scraping the info from the web I would recommend WatiN or Selenium



回答4:

You can try using RawViewWalker on a element to get raw values (On controlview you might not be able to get few properties)