整理 | 小耕家的喵大仙
出品 | 优快云(ID:lichao19897314)
关联源码及工具下载
https://download.youkuaiyun.com/download/lichao19897314/90096681
往期知识回顾:
(18)C#采集微信群群成员列表信息-微信UI自动化(.Net)
👆😀以上文章是以往使用自动化方案操作微信的一些案例!如有兴趣请点击浏览!
实现思路:
因为操作的对象是微信窗体,所以我们需要对针对微信窗体构造一个自动化对象
(1)通过微信窗体名称找到微信句柄的指针。
(2)通过微信句柄指针寻找到微信的进程ID。
(3)使用微信进程ID初始化自动化组件。
(4)通过自动化组件将微信窗体的状态设为激活。
核心代码片段:
(1)定义两个Win Api函数,分别为获取窗体句柄和获取进程ID
//根据名称获取窗体句柄
[DllImport("user32.dll", EntryPoint = "FindWindowEX")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
//根据句柄获取进程ID
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
以上函数只是基础底层实现,请先定义即可!
(2)通过WinApi获取微信窗口句柄和进程ID
int weChatID = 0;
IntPtr hwnd = FindWindow(null, "WeChat");
if (hwnd != IntPtr.Zero)
{
GetWindowThreadProcessId(hwnd, out weChatID);
}
如果找到了微信句柄和进程ID即可继续操作,没有那么请检查是否已运行和登录微信。
(3)根据进程ID初始化自动化组件
//根据微信进程ID绑定FLAUI
var application = Application.Attach(weChatID);
var automation = new UIA3Automation();
//获取微信window自动化操作对象
var Window = application.GetMainWindow(automation);
(4)将微信窗体激活(最大化,恢复默认)
public void Focus()
{
if (window.AsWindow().Patterns.Window.PatternOrDefault != null)
{
//将微信窗体设置为默认焦点状态
window.AsWindow().Patterns.Window.Pattern.SetWindowVisualState(FlaUI.Core.Definitions.WindowVisualState.Normal);
}
}
上一篇 (1)C#开启探索微信自动化之路-微信UI自动化https://blog.youkuaiyun.com/lichao19897314/article/details/122719220
下一篇 (3)C#针对系统热键管理-微信UI自动化https://blog.youkuaiyun.com/lichao19897314/article/details/122720286