###前提・実現したいこと
C#でUI テストを行うためにUI Automationについて調べていました。
電卓を用いたサンプルは以下のサイトの通り行い、無事動かすことが出来ました。
http://tercel-tech.hatenablog.com/entry/2015/04/29/181723
試しに電卓ではなく、「スクリーンキーボード」※1で何かキーを押すのを自分で実装しようとしたところ、
うまくキーの要素が取得できないため、キーがクリックできませんでした。
※1 スクリーンキーボード(%windir%\system32\osk.exe)
###発生している問題・エラーメッセージ
子要素が取得できない為、ハマっています。
###該当のソースコード
C#
1using System; 2using System.Collections.Generic; 3using System.Diagnostics; 4using System.IO; 5using System.Linq; 6using System.Runtime.InteropServices; 7using System.Text; 8using System.Threading; 9using System.Threading.Tasks; 10using System.Windows.Automation; 11using Winium.Cruciatus; 12using Winium.Cruciatus.Core; 13using Winium.Cruciatus.Extensions; 14 15namespace testxxx 16{ 17 class Program 18 { 19 // 指定したID属性に一致するAutomationElementを返します 20 static AutomationElement FindElementById(AutomationElement rootElement, string automationId) 21 { 22 return rootElement.FindFirst( 23 TreeScope.Element | TreeScope.Descendants, 24 new PropertyCondition(AutomationElement.AutomationIdProperty, automationId)); 25 } 26 27 // 指定したName属性に一致するAutomationElementをすべて返します 28 static IEnumerable<AutomationElement> FindElementsByName(AutomationElement rootElement, string name) 29 { 30 return rootElement.FindAll( 31 TreeScope.Element | TreeScope.Descendants, 32 new PropertyCondition(AutomationElement.NameProperty, name)) 33 .Cast<AutomationElement>(); 34 } 35 36 // 指定したName属性に一致するボタン要素をすべて返します 37 static IEnumerable<AutomationElement> FindButtonsByName(AutomationElement rootElement, string name) 38 { 39 const string BUTTON_CLASS_NAME = "Button"; 40 return from x in FindElementsByName(rootElement, name) 41 where x.Current.ClassName == BUTTON_CLASS_NAME 42 select x; 43 } 44 45 static void Main(string[] args) 46 { 47 if (Process.GetProcessesByName("osk").Count() <= 0) 48 { 49 Console.WriteLine($"Please launch osk.exe"); 50 return; 51 } 52 53 var mainForm = AutomationElement.FromHandle(Process.GetProcessesByName("osk").First().MainWindowHandle); 54 Console.WriteLine(mainForm.Current.NativeWindowHandle); 55 56 var btnClear = FindElementsByName(mainForm, "").First(); 57 Console.WriteLine(btnClear.Current.NativeWindowHandle); 58 59 // ココで要素の取得ができていない 60 var xx = btnClear.FindAll(TreeScope.Children | TreeScope.Descendants, 61 new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button)); 62 63 Console.WriteLine(xx.Count); 64 //Console.WriteLine(xx.Current.NativeWindowHandle); 65 66 Console.ReadKey(); 67 } 68 } 69}
###試したこと
・管理者権限で起動
→関係がなかった
