赞
踩
.net core
以上版本的项目需要设置目标os为windows
Main
方法需要[STAThread]
标记
using FlaUI.Core;
using FlaUI.Core.AutomationElements;
using FlaUI.Core.Conditions;
using FlaUI.Core.Input;
using FlaUI.Core.WindowsAPI;
using FlaUI.UIA3;
internal class Program { [DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)] static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow); [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll", SetLastError = true)] internal static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); [STAThread] static void Main(string[] args) { // 设置控制台程序窗口位置和大小 IntPtr ptr = GetConsoleWindow(); MoveWindow(ptr, 0, 0, 200, 100, true); Process[] processes = Process.GetProcessesByName("WeChat"); if (processes.Count() != 1) { Console.WriteLine("微信未启动或启动多个微信"); } else { //1.附加到微信进程 using (var app = Application.Attach(processes.First().Id)) { using (var automation = new UIA3Automation()) { //2.获取主界面 var mainWindow = app.GetMainWindow(automation); Console.WriteLine("获取主界面"); //3.切换到通讯录 var elements = mainWindow.FindAll(FlaUI.Core.Definitions.TreeScope.Subtree, TrueCondition.Default); var addressBook = mainWindow.FindFirstDescendant(cf => cf.ByName("通讯录")); addressBook.DrawHighlight(System.Drawing.Color.Red); Console.WriteLine("点击通讯录"); addressBook.Click(); // 4.搜索 string target = "文件传输助手"; var searchTextBox = mainWindow.FindFirstDescendant(cf => cf.ByName("搜索")).AsTextBox(); searchTextBox.Click(); Keyboard.Type(target); Keyboard.Type(VirtualKeyShort.RETURN); Console.WriteLine("搜索目标对象"); //5.切换到对话框 Thread.Sleep(500); var searchList = mainWindow.FindFirstDescendant(cf => cf.ByName("搜索结果")); if (searchList != null) { // cf.Name.Contains(target) 模糊查询,也可以 cf.Name==target 精确查询 var searchItem = searchList.FindAllDescendants().FirstOrDefault(cf => cf.Name.Contains(target) && cf.ControlType == FlaUI.Core.Definitions.ControlType.ListItem); searchItem?.DrawHighlight(System.Drawing.Color.Red); searchItem?.AsListBoxItem().Click(); } else { Console.WriteLine("没有搜索到内容"); return; } Thread.Sleep(500); //6.输入文本 string sendMsg = "自动消息测试"; var msgInput = mainWindow.FindFirstDescendant(cf => cf.ByName("输入")).AsTextBox(); if (msgInput == null) return; msgInput?.Click(); System.Windows.Forms.Clipboard.SetText(sendMsg); Keyboard.TypeSimultaneously(new[] { VirtualKeyShort.CONTROL, VirtualKeyShort.KEY_V }); Thread.Sleep(500); //按下回车 Keyboard.Press(VirtualKeyShort.ENTER); //点击发送按钮 //var sendBtn = mainWindow.FindFirstDescendant(cf => cf.ByName("发送(S)")); //Console.WriteLine(sendBtn.Name); //sendBtn?.DrawHighlight(System.Drawing.Color.Red); //sendBtn?.Click(); } } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。