首页 > 解决方案 > 如何从 UIAutomation 获取隐藏/私有 UI 元素,我可以在 Spy++ 中看到它,但无法在代码中找到它,只有它的父母和兄弟姐妹

问题描述

我正在尝试使用 System.Windows.Automation 来访问 VLC 媒体播放器中的 UI 元素(特别是最左角的状态框,显示当前正在播放的视频的文件名)。我可以获取父元素和兄弟元素,但在 Spy++ 中,所有旁边有一个灰色图标的元素我无法在代码中访问...我假设灰色图标意味着它们是私有的或隐藏的或类似的东西. 这是一张显示我的意思的图片:

在此处输入图像描述

请注意,我有一个使用句柄 0x30826 对父级的引用,我从中执行 FindAll()* 并最终得到一个结果,即对句柄为 0x30858 的子级的引用。您可以在 Spy++ 中看到 0x30826 的 5 个孩子,但只有一个,我在 FindAll 时得到的那个,有一个全黑图标,其他有一个灰色图标,我无法找到它们。另请注意,我想要的是 0x20908 并且它有一个灰色图标...

我怎样才能在代码中做到这一点?

*这是我用来尝试获取 0x30826 的所有孩子的代码:

    Dim aeDesktop As AutomationElement
    Dim aeVLC As AutomationElement
    Dim c As AutomationElementCollection
    Dim cd As New AndCondition(New PropertyCondition(AutomationElement.IsEnabledProperty, True), New PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.StatusBar))

    aeVLC = aeDesktop.FindFirst(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "got s01e01.avi - VLC media player"))

    c = aeVLC.FindAll(TreeScope.Children, cd)

    c = c(0).FindAll(TreeScope.Children, Condition.TrueCondition)

第一个 FindAll() 只给我 0x30826,这很好,因为这就是我想要的,但是第二个 FindAll,没有指定条件,当我可以看到它时只给出 0x30858 加上 Spy++ 中的其他 4 个,包括我想要的那个。

标签: windowsvb.netui-automationspy++

解决方案


使用 Spy++ 而不是Inspect Program确实妨碍了您的工作。使用 Inspect,您可以轻松地看到目标元素是一个文本元素,其父级是状态栏元素,而状态栏元素又是主窗口元素的父级。

检查中的 VLC

使用该信息,获取对目标文本元素的引用非常简单。首先获取主窗口,然后是状态栏,最后是状态栏的第一个文本元素。

' find the VLC process 
Dim targets As Process() = Process.GetProcessesByName("vlc")

If targets.Length > 0 Then

    ' assume its the 1st process 
    Dim vlcMainWindowHandle As IntPtr = targets(0).MainWindowHandle

    ' release all processes obtained
    For Each p As Process In targets
        p.Dispose()
    Next

    ' use vlcMainWindowHandle to get application window element
    Dim vlcMain As AutomationElement = AutomationElement.FromHandle(vlcMainWindowHandle)

    ' get the statusbar
    Dim getStatusBarCondition As Condition = New PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.StatusBar)
    Dim statusBar As AutomationElement = vlcMain.FindFirst(TreeScope.Children, getStatusBarCondition)

    ' get the 1st textbox in the statusbar
    Dim getTextBoxCondition As Condition = New PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text)
    Dim targetTextBox As AutomationElement = statusBar.FindFirst(TreeScope.Children, getTextBoxCondition)

    ' normally you use either a TextPattern.Pattern or ValuePattern.Pattern
    ' to obtain the text, but this textbox exposes neither and it uses the
    ' the Name property for the text.

    Dim textYouWant As String = targetTextBox.Current.Name

End If

推荐阅读