进行微信自动化前,因为采集或者发送消息任务执行需要时间,并且微信窗体会将焦点长期占有,导致我们对软件失去控制,所以我们需要使用热键的方式将任务停止。我们这里采用热键是![]()
编辑。
(1)编写一个热键管理类
这个类定义了捕获热键消息的ID,注册热键,注销热键的功能。
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事件中注册热键
this.Load += WXUIAuto_Load;
private void WXUIAuto_Load(object sender, EventArgs e)
{
WinHotKey.RegisterStop(this.Handle);
}
在窗体关闭事件中注销事件
this.FormClosed += WXUIAuto_FormClosed;
private void WXUIAuto_FormClosed(object sender, FormClosedEventArgs e)
{
WinHotKey.UnRegisterStop(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就停止微信自动化任务。
接下来我们进行联系人采集学习
因为文章所表达的意思可能无法满足每一位阅读需求,需要源码或者支持请联系作者QQ 978124155