(2)PC微信UI自动化-微信窗体自动化初始化(C#)

发布时间 2023-11-02 14:30:07作者: 小耕养了只喵大仙

 我们接下来的操作的对象是微信窗体,分成这几个步骤可以将微信窗体进行自动化操作前的初始化

(1)通过窗体名称找到微信句柄指针。

(2)通过窗体指针找到微信的进程ID。

(3)使用进程ID初始化自动化组件服务。

(4)设置微信窗体的状态为激活。

(1)找到PC端微信窗体并获取微信窗体的句柄数据

 我们借助WINDOWS的两个API函数 ,先定义好API的C#调用方式。

 //根据名称获取窗体句柄
[DllImport("user32.dll", EntryPoint = "FindWindow")]
   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)通过以下代码获取到微信的窗口句柄和进程ID

int weChatID = 0;

IntPtr hwnd = FindWindow(null, "微信");

if (hwnd != IntPtr.Zero)
{
   GetWindowThreadProcessId(hwnd, out weChatID);
}

如果找到了微信句柄那么就可以继续了,如果没有那么请扫描登录或者进行其他的操作。比如自动打开微信。

(3)使用FlaUI.Core组件根据进程ID初始化自动化组件

 //根据微信进程ID绑定FLAUI
 var application = FlaUI.Core.Application.Attach(weChatID);

 var automation = new UIA3Automation();

 //获取微信window自动化操作对象
 var Window = application.GetMainWindow(automation);

自动化FlaUI对象构造就是通过步骤一获取微信进程ID进行构造。

(4)如果用户将微信最小化,我们需要将微信窗体置顶激活或者最大化

     public void Focus()
        {
            
            if (window.AsWindow().Patterns.Window.PatternOrDefault != null)
            {
                //将微信窗体设置为默认焦点状态
window.AsWindow().Patterns.Window.Pattern.SetWindowVisualState(FlaUI.Core.Definitions.WindowVisualState.Normal);
            }
        }

这个方法可以将微信窗体设置为活动焦点状态。

 

因为文章所表达的意思可能无法满足每一位阅读需求,需要源码或者支持请联系作者QQ 978124155