整理 | 小耕家的喵大仙
出品 | CSDN(ID:lichao19897314)
Q Q | 978124155
往期知识回顾:
(1)C#开启探索微信自动化之路-微信UI自动化
👆 以上文章是以往对使用自动化技术操作微信的一些文章及案例!!!!
微信定时发送消息
(1)自动化程序在运行过程中应为依赖的主程序是微信,所以要对微信进程运行状态进行监控,如果发现微信处于运行状态的情况则自动化程序可以执行对应操作,微信应为人为或者意外导致关闭的情况则需要自动化程序马上响应做出对应的处理。
(2)实现思路,开启一个线程定时监控微信的窗体是否存在则可以实现
实现过程
首先定义一个WIN32 API的调用类,用来查找窗体。
/// <summary>
/// 发现窗口
/// </summary>
public class Win32_Find_Window
{
[DllImport("user32.dll", EntryPoint = "FindWindow")]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
public static IntPtr Do(string className, string windowName)
{
return FindWindow(className, windowName);
}
}
定义好一个查找微信窗体的调用类
public class WXWin32
{
private static IntPtr currentWeixin = IntPtr.Zero;
public static IntPtr GetWeiXin()
{
// if (currentWeixin == IntPtr.Zero)
currentWeixin = Win32_Find_Window.Do("WeChatMainWndForPC", "微信");
return currentWeixin;
}
}
定义一个监控的基类,因为后续很多监控都需要
public class BaseMonitor : IMonitor
{
public BaseMonitor() {
MonitorStatus = MonitorStatus.Stop;
}
public MonitorStatus MonitorStatus { get; protected set; }
public event EventHandler<EventArgs> MonitorStop;
public virtual void Break()
{
MonitorStatus = MonitorStatus.Stoping;
}
public virtual void Monitor()
{
}
protected void ExecuteMonitorStop()
{
MonitorStatus = MonitorStatus.Stop;
if (MonitorStop != null)
{
MonitorStop(this, EventArgs.Empty);
}
}
}
public enum MonitorStatus
{
Monitoring = 0,
Stoping = 1,
Stop = 2
}
定义监控类
namespace WpfApp1.UIAuto.Monitor
{
public class UI_WX_Process_Monitor : BaseMonitor
{
public event EventHandler<ProcessEventArgs> ProcessEvent;
public ProcessStatus Status { get; private set; } = ProcessStatus.UnKnow;
public override void Monitor()
{
if (MonitorStatus == MonitorStatus.Monitoring)
return;
SystemLog.Info("启动微信是否打开监听");
MonitorStatus = MonitorStatus.Monitoring;
Thread th = new Thread(new ThreadStart(() =>
{
while (MonitorStatus == MonitorStatus.Monitoring)
{
if (WXWin32.GetWeiXin() != IntPtr.Zero)
{
DoProcess(ProcessStatus.Run);
}
else
{
DoProcess(ProcessStatus.Close);
}
Thread.Sleep(1000);
}
ExecuteMonitorStop();
}));
th.Start();
}
private void DoProcess(ProcessStatus status)
{
if (Status == status)
return;
Status = status;
if (ProcessEvent != null)
{
ProcessEvent(this, new ProcessEventArgs { Status = status });
}
}
public override void Break()
{
base.Break();
SystemLog.Info("关闭微信是否打开监听");
}
}
public class ProcessEventArgs : EventArgs
{
public ProcessStatus Status { get; set; }
}
public enum ProcessStatus
{
UnKnow = 0,
Run = 1,
Close= 2
}
}
调用
public MainWindow()
{
UI_WX_Process_Monitor process = new UI_WX_Process_Monitor();
process.ProcessEvent += Process_ProcessEvent;
process.Monitor();
}
private void Process_ProcessEvent(object sender, ProcessEventArgs e)
{
if (e.Status == ProcessStatus.Close)
{
//你的具体业务代码
}
}
上一篇(7)微信UI自动化-自动发送消息给指定联系人(C#)(.Net)
因为文章所表达的意思可能无法满足每一位阅读需求,需要源码或者支持请联系作者QQ 978124155