整理 | 小耕家的喵大仙
出品 | CSDN(ID:lichao19897314)
Q Q | 978124155
往期知识回顾:
👆 以上文章是以往对使用自动化技术操作微信的一些文章及案例!!!!
因为文章可能无法满足读者要求,如需源码和支持请联系本人QQ 978124155
本篇目的
我们对微信UI自动化操作或者其它软件UI自动化操作之前,因为一些任务比如“采集微信通讯录”和“群发消息”,“获取微信聊天记录”等执行可能比较耗时,并且会导致被控制方软件窗体长期获得焦点导致我们对其它软件失去控制权,所以我们需要使用热键的方式将自动化任务停止。本文中采用热键是Ctrl+F8。
实现思路
(1)定义热键注册管理类
这个类定义了注册热键,捕获热键消息,注销热键的基本功能。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OnlineRetailers.Extension.Page.UIAuto.Business
{
/// <summary>
/// 热键管理
/// </summary>
public class WinHotKey
{
/// <summary>
/// 注册热键
/// </summary>
/// <param name="hWnd">为窗口句柄</param>
/// <param name="id">注册的热键识别ID</param>
/// <param name="control">组合键代码 Alt的值为1,Ctrl的值为2,Shift的值为4,Shift+Alt组合键为5
/// Shift+Alt+Ctrl组合键为7,Windows键的值为8
/// </param>
/// <param name="vk">按键枚举</param>
/// <returns></returns>
[DllImport("user32")]
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys vk);
/// <summary>
/// 取消注册的热键
/// </summary>
/// <param name="hWnd">窗口句柄</param>
/// <param name="id">注册的热键id</param>
/// <returns></returns>
[DllImport("user32")]
static extern bool UnregisterHotKey(IntPtr hWnd, int id);
/// <summary>
/// 任务停止热键
/// </summary>
/// <param name="Handle"></param>
public static void RegisterStop(IntPtr Handle)
{
WinHotKey.RegisterHotKey(Handle, StopId, 2, Keys.F8);
}
/// <summary>
/// 取消停止热键
/// </summary>
/// <param name="Handle"></param>
public static void UnRegisterStop(IntPtr Handle)
{
WinHotKey.UnregisterHotKey(Handle, StopId);
}
/// <summary>
/// 停止ID
/// </summary>
public static readonly int StopId = 8879;
}
}
(2)主窗体调用注册热键,执行热键方法和注销热键
在我们测试软件的主窗体Load事件中注册热键,将窗体的句柄传递给热键管理类,那么热键被激活时则会通过win消息的方式通知本窗体。
this.Load += WXUIAuto_Load;
private void WXUIAuto_Load(object sender, EventArgs e)
{
WinHotKey.RegisterStop(this.Handle);
}
注册了热键事件后我们需要定义方法来监听热键的事件,From窗体中提供了处理消息WndProc方法,我们重写这个方法,并加入自己的逻辑。
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x0312:
if (m.WParam.ToString().Equals(WinHotKey.StopId.ToString()))
{
//停止微信自动化任务
}
break;
}
base.WndProc(ref m);
}
0x0312是热键的消息类型,消息参数是我们自己定义的,如果热键的消息参数等于停止的ID 8897就停止微信自动化任务。
在窗体关闭事件中注销事件,确保资源的释放和安全。
this.FormClosed += WXUIAuto_FormClosed;
private void WXUIAuto_FormClosed(object sender, FormClosedEventArgs e)
{
WinHotKey.UnRegisterStop(this.Handle);
}
上一篇 (2)C#创建微信窗体自动化实例-微信UI自动化https://blog.csdn.net/lichao19897314/article/details/122719767
下一篇 (4)C#采集微信通讯录和联系人-微信UI自动化https://blog.csdn.net/lichao19897314/article/details/122823991
因为文章可能无法满足读者要求,如需源码和支持请联系本人QQ 978124155