標籤:
UIAutomation比API的優點是類似於訊息處理機制,而不是主要靠類比滑鼠鍵盤發送訊息
首先添加引用UIAutomationClient和UIAutomationTypes,在安裝.net3.5的電腦上可用。低版本的VS可以直接引用dll。
using System.Windows.Automation;
//先用傳統方法找到hwnd,用UI也能找到,新項目應統一到UI
IntPtr leftview = API.FindWindowEx(wd0, 0, "SysListView32", "CFQS");
IntPtr rightview = API.FindWindowEx(wd0, 0, "SysListView32", "List2");
if (leftview == IntPtr.Zero || rightview == IntPtr.Zero) return;
AutomationElement el = AutomationElement.FromHandle(leftview); //左側view
AutomationElement er = AutomationElement.FromHandle(rightview); //右側view
PropertyCondition condition_bk = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem); //尋找子視窗的條件 同樣是ListViewItem,對左邊的只能用ControlType.DataItem,右邊的用ControlType.ListItem
AutomationElementCollection bks = el.FindAll(TreeScope.Children, condition_bk); //獲得所有滿足條件子視窗的集合
//還有一種遍曆子視窗的方法 用TreeWalker
//AutomationElement el = AutomationElement.FromHandle(leftview);
//TreeWalker walker = TreeWalker.ContentViewWalker;
//for (AutomationElement child = walker.GetFirstChild(el); child != null; child = walker.GetNextSibling(child)) //{
// string name=child.Current.Name
//}
API.mouse_event((int)(MouseEventFlags.Wheel | MouseEventFlags.Absolute), 0, 0, -380, IntPtr.Zero); //讓捲軸下滾,僅為視覺效果,不要也行
SelectionItemPattern selPattern = (SelectionItemPattern)item.GetCurrentPattern(SelectionItemPattern.Pattern);
selPattern.Select(); //選擇該板塊 //實現ListView內部元素選擇
// item.Current.Name 可取出Listview內部元素內容
//PropertyCondition condition = new PropertyCondition(AutomationElement.IsEnabledProperty, true); //可通用所有非禁用項作為類型
2016.9.2補充
往控制項中輸入內容
AutomationElement element = AutomationElement.FromHandle(edbox);
object valuePattern = null;
if (element.TryGetCurrentPattern(ValuePattern.Pattern, out valuePattern)) //是否支援直接寫入
{
// Set focus for input functionality and begin.
element.SetFocus();
((ValuePattern)valuePattern).SetValue(fullpath);
}
else //否則類比鍵入
{
// Set focus for input functionality and begin.
element.SetFocus();
// Pause before sending keyboard input.
Thread.Sleep(100);
// Delete existing content in the control and insert new content.
SendKeys.SendWait("^{HOME}"); // Move to start of control
SendKeys.SendWait("^+{END}"); // Select everything
SendKeys.SendWait("{DEL}"); // Delete selection
SendKeys.SendWait(fullpath);
}
2015.4.25利用UIAutomation 替代API函數,解決了ListView無法讀資料的難題,順便實現了滑鼠類比滾輪