UI自动化和.net技术下的Datagrid内容

6

我在使用UI自动化读取外部应用程序中Datagrid的内容时遇到了一些问题,希望能得到一些指导。以下是我目前已经完成的部分:

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;

从GridItemPattern和TableItemPattern中,我可以访问列ID和行ID,但是如何访问特定单元格中的值呢?这是否可能?

谢谢。

4个回答

1
我认为你需要使用 ValuePattern。就像这样:
ValuePattern pattern = items[0].GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
string value = pattern.Current.Value;

谢谢,不幸的是,在尝试获取值模式时,我遇到了“不支持的模式”异常。 UISpy仅显示GridItem和TableItem作为有效模式。还有其他想法吗? :) - ChrisO
很遗憾 =( 在我的测试应用程序中,单元格中显示的值也包含在单元格的AutomationElementInformation元素的Name字段中(对于您的示例,为items[1].Current.Name - Natalia

1

我终于弄清楚了,需要使用CacheRequest来请求AutomationElement上的Name属性。这是最终的代码:

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;

0

我不熟悉AutomationElement类,但我曾经使用AutoIT自动化一些简单的Windows操作(查找对话框、点击按钮等),非常容易上手。你可以考虑使用它。下载包含一个.dll文件,你可以从.Net解决方案中引用它。

我不确定外部应用程序是否是WinForm网格,但这里有一个ASP.Net网格示例:http://www.autoitscript.com/forum/topic/13709-how-to-get-the-contents-of-datagrid-control/

另外,如果你正在从Web上抓取信息,我建议使用WatiNSelenium


嘿,我过去经常使用AutoIT和一些AutoITX库,但是我甚至无法在其Window Info应用程序中看到外部应用程序中的datagrid。我认为这是一个WPF应用程序,每个控件都在包装器中。我想使用AutomationElement的原因是因为我可以在UISpy中看到DataGrid,所以我假设可以提取值,但现在看来似乎不可能。 - ChrisO

0

您可以尝试在元素上使用RawViewWalker来获取原始值(在ControlView上,您可能无法获取一些属性)


1
这是针对MoMo的答案的评论吗? - Flexo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接