SoftwareEngineering/ProgramLanguage/VB.NET
Imports System.Windows.Automation
Public Class Form1
Public Declare Function FindWindowEx Lib "user32.dll" Alias "FindWindowExA" (ByVal hwndParent As Integer, ByVal hwndChildAfter As Integer, ByVal lpszClass As String, ByVal lpszWindow As String) As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim windowTitle As String = "Form1"
Dim windowHandle As Integer = FindWindow(windowTitle)
Dim form As AutomationElement = AutomationElement.FromHandle(windowHandle)
Dim txtElement As AutomationElement = FindElement(form, "TextBox1")
Dim vpTxtInput As ValuePattern = CType(txtElement.GetCurrentPattern(ValuePattern.Pattern), ValuePattern)
Dim cmbElement As AutomationElement = FindElement(form, "ComboBox1")
Dim rdoElement1 As AutomationElement = FindElement(form, "RadioButton1")
Catch ex As Exception
Call MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim windowTitle As String = "Form1"
Dim windowHandle As Integer = FindWindow(windowTitle)
Dim form As AutomationElement = AutomationElement.FromHandle(windowHandle)
Dim txtElement As AutomationElement = FindElement(form, "TextBox1")
Dim tpTxtInput As TextPattern = CType(txtElement.GetCurrentPattern(TextPattern.Pattern), TextPattern)
MsgBox(tpTxtInput.DocumentRange.GetText(-1))
Dim cmbElement As AutomationElement = FindElement(form, "ComboBox1")
Dim rdoElement1 As AutomationElement = FindElement(form, "RadioButton1")
Dim chkElement As AutomationElement = FindElement(form, "CheckBox1")
Dim IsSelected As Boolean = False
Dim objPattern As Object = Nothing
Dim togPattern As TogglePattern
If True = chkElement.TryGetCurrentPattern(TogglePattern.Pattern, objPattern) Then
togPattern = TryCast(objPattern, TogglePattern)
IsSelected = (togPattern.Current.ToggleState = ToggleState.On)
End If
MsgBox(IsSelected)
Catch ex As Exception
Call MsgBox(ex.Message)
End Try
End Sub
Public Function FindWindow(ByVal windowTitle As String) As Integer
Dim windowHandle As Integer = FindWindowEx(0, 0, vbNullString, windowTitle)
If (0 = windowHandle) Then
Throw New Exception(String.Format("ウィンドが見つかりませんでした。{0}....タイトル:[{1}]", vbCrLf, windowTitle))
End If
Return windowHandle
End Function
Private Function FindElement(ByVal rootElement As AutomationElement, ByVal automationId As String) As AutomationElement
Dim element As AutomationElement = rootElement.FindFirst(TreeScope.Element Or TreeScope.Descendants, New PropertyCondition(AutomationElement.AutomationIdProperty, automationId))
If (element Is Nothing) Then
Throw New Exception(String.Format("コントロールが見つかりませんでした。{0}....コントロール名:[{1}]", vbCrLf, automationId))
End If
Return element
End Function
End Class