如何解决Windows 10 计算器上的 C# 自动化单击按钮
所以我是 C# 的新手,我想做一个自动化,可以点击 Win10 计算器上的几个按钮 我下载了 LeanRunner Designer 并使用它的模型管理器来获取数字 5 的计算器按钮属性,我得到了:
Auto.getwindow({
"className": "ApplicationFrameWindow","title": "Calculator"
}).getwindow({
"className": "Windows.UI.Core.CoreWindow","title": "Calculator"
}).getGeneric({
"type": "Group","automationId": "NumberPad","name": "Number pad","className": "NamedContainerAutomationPeer"
}).getButton({
"automationId": "num5Button","name": "Five","className": "Button"
}).click(52,24);
我像这样转移了 getwindow 并且有效
int hwnd=0;
IntPtr hwndChild=IntPtr.Zero;
IntPtr hwndChild2 = IntPtr.Zero;
//Get a handle for the Calculator Application main window
hwnd = FindWindow("ApplicationFrameWindow","Calculator");
hwndChild = findwindowex((IntPtr)hwnd,IntPtr.Zero,"Windows.UI.Core.CoreWindow","Calculator");
但现在我需要点击按钮,但我被卡住了。 我知道点击的最终结果是
SendMessage((int)hwndChild2,BM_CLICK,IntPtr.Zero);
但是我缺少到达按钮位置的部分。 我不想使用 SendKeys。 谢谢,如果我错过了什么或不清楚。
解决方法
如上所述,这可以通过 UIAutomation 来完成。 例如像这样:
public static AutomationElement calcUI;
public void FindAndClickButton(string name)
{
System.Windows.Automation.Condition condition1 = new PropertyCondition(AutomationElement.ClassNameProperty,"Button");
System.Windows.Automation.Condition condition2 = new PropertyCondition(AutomationElement.NameProperty,name);
System.Windows.Automation.Condition condition = new AndCondition(condition1,condition2);
AutomationElement button = calcUI.FindFirst(TreeScope.Descendants,condition);
InvokePattern btnPattern = button.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
btnPattern.Invoke();
}
private void Button_Click(object sender,RoutedEventArgs e)
{
var calc = System.Diagnostics.Process.Start("calc");
//wait for the UI to appear
calc.WaitForInputIdle(5000);
System.Threading.Thread.Sleep(2000);
AutomationElement root = AutomationElement.RootElement;
System.Windows.Automation.Condition condition = new PropertyCondition(AutomationElement.NameProperty,"Calculator");
calcUI = root.FindFirst(TreeScope.Children,condition);
if (calcUI != null)
{
// get and click the buttons for the calculation
FindAndClickButton("Five");
FindAndClickButton("Plus");
FindAndClickButton("Nine");
FindAndClickButton("Multiply by");
FindAndClickButton("Three");
FindAndClickButton("Divide by");
FindAndClickButton("Four");
FindAndClickButton("Equals");
//get the result
System.Windows.Automation.Condition conditionResult = new PropertyCondition(AutomationElement.AutomationIdProperty,"CalculatorResults");
var result = calcUI.FindFirst(TreeScope.Descendants,conditionResult);
MessageBox.Show(result.Current.Name);
}
}
不要忘记添加对项目的引用
UIAutomationClient
UIAutomationTypes
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。