Hello 朋友们大家好,我们接着上一节:C# .NET基于FlaUIAutomation开发PC端微信机器人#1继续我们的微信机器人开发,本节要实现的内容是获取当前聊天对象的聊天记录。
首先,必不可少的安装相关库以及初始化FlaUIAutomation本节将不在重复,不清楚的朋友烦请移步上一节文章,话不多说,直接上代码:
public static List<Dictionary<string, string>> GetAllChatRecords()
{
List<Dictionary<string, string>> chatRecords = new List<Dictionary<string, string>>();
using (var automation = new UIA3Automation())
{
// 获取聊天记录的父元素对象
var messageWindowElement = weChatWindow.FindFirstDescendant(cf => cf.ByName("消息"));
// 获取聊天记录的列表项元素(消息列表)
var messageListItems = messageWindowElement.FindAll(TreeScope.Subtree, new PropertyCondition(AutomationObjectIds.ControlTypeProperty, ControlType.ListItem));
// 遍历聊天记录列表项
foreach (var messageListItem in messageListItems)
{
// 获取每条聊天记录对应的用户按钮元素
var userButtonElements = messageListItem.FindAll(TreeScope.Subtree, new PropertyCondition(AutomationObjectIds.ControlTypeProperty, ControlType.Button));
// 创建字典保存聊天记录信息
Dictionary<string, string> chatRecord = new Dictionary<string, string>();
// 遍历用户按钮元素
foreach (var userButtonElement in userButtonElements)
{
// 只有包含发送者的用户按钮才视为有效聊天记录
if (!string.IsNullOrEmpty(userButtonElement.Name))
{
// 将发送者和聊天信息添加到字典中
chatRecord["Sender"] = userButtonElement.Name;
chatRecord["Message"] = messageListItem.Name;
Console.WriteLine(userButtonElement.Name + ":" + messageListItem.Name);
}
}
// 将聊天记录字典添加到列表中
chatRecords.Add(chatRecord);
}
}
return chatRecords;
}
运行代码,查看效果:
代码的的具体作用,我已经注释的非常清楚,最后需要再次强调:基于UI自动化库开发的重点是要对自动化目标程序的元素树结构充分了解,分析微信元素结构的工具有很多,我个人自用的在上一节已经分享了,需要的朋友请移步上一节文章,谢谢大家,下节再见~~