如何使用UI Automation选择树项?

时间:2013-05-10 22:02:54

标签: c# .net visual-studio ui-automation

我正在尝试从应用程序中选择一个树项但得到“无法执行操作”。我尝试使用UI Spy来选择树项并得到相同的错误。

  

元素:“树项目”“网络”   名称:InvalidOperationException   消息:无法执行操作。   堆栈跟踪:在MS.Internal.AutomationProxies.WindowsTreeView.TreeViewItem.System.Windows.Automation.Provider.ISelectionItemProvider.Select()      在System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode,IntPtr errorInfo)      在MS.Internal.Automation.UiaCoreApi.CheckError(Int32 hr)      在System.Windows.Automation.SelectionItemPattern.Select()

从UI Spy我知道SelectionItem是一种受支持的模式。这是一些代码

AutomationElement  Item = _ParentNode.FindFirst(TreeScope.Descendants, new AndCondition(
            new PropertyCondition(AutomationElement.NameProperty, "Network"),
            new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TreeItem)));

SelectionItemPattern ItemToSelect = Item .GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
ItemToSelect.Select();

知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

如果自动化元素“Item”支持SelectionPattern控件模式,请以编程方式验证。

private SelectionPattern GetSelectionPattern(
AutomationElement targetControl)
{
SelectionPattern selectionPattern = null;

try
{
    selectionPattern =
        targetControl.GetCurrentPattern(SelectionPattern.Pattern)
        as SelectionPattern;
}
// Object doesn't support the SelectionPattern control pattern 
catch (InvalidOperationException)
{
    return null;
}

return selectionPattern;

}

来源:https://msdn.microsoft.com/en-us/library/ms604455(v=vs.110).aspx