添加引用
.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
{
using (var app = Application.Attach(processes.First().Id))
{
using (var automation = new UIA3Automation())
{
var mainWindow = app.GetMainWindow(automation);
Console.WriteLine("获取主界面");
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();
string target = "文件传输助手";
var searchTextBox = mainWindow.FindFirstDescendant(cf => cf.ByName("搜索")).AsTextBox();
searchTextBox.Click();
Keyboard.Type(target);
Keyboard.Type(VirtualKeyShort.RETURN);
Console.WriteLine("搜索目标对象");
Thread.Sleep(500);
var searchList = mainWindow.FindFirstDescendant(cf => cf.ByName("搜索结果"));
if (searchList != null)
{
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);
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);
}
}
}
}
}
三级目录