需求是这样:
1.有一个注册程序,每隔4个小时就会失效,需要每隔4个小时,重启注册程序,然后还要自动单击上面的“启动验证”按钮;
2.当程序产生一个错误日志文件时,重启注册程序,然后还要自动单击上面的“启动验证”按钮。
思路:
1.先找到注册程序的主窗口句柄;
2.根据主窗口句柄找到"启动验证"按钮;
3.向按钮发生单击消息.
代码如下:
string _exePath = string.Empty;
//主窗口句柄
IntPtr _mainIntPtr=IntPtr.Zero;
//按钮句柄
IntPtr _buttonIntPtr=IntPtr.Zero;
//此处用于取得计算器窗口的句柄
[DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow);
//此处用于向窗口发送消息
[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
private static extern void SetForegroundWindow(IntPtr hwnd);
[DllImport("user32.dll")]
static extern IntPtr SetActiveWindow(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
//每10秒钟轮询一次
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 10000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
//错误日志路径
string _errPath=string.Empty;
//注册程序路径
string _exePath=string.Empty;
const uint BM_CLICK = 0xF5; //鼠标点击的消息
DateTime _startDateTime=DateTime.Now;
DateTime _currDateTime;
private void timer_Tick(object sender, EventArgs e)
{
_errPath=this.textBox1.Text.Trim();
_exePath = this.textBox2.Text.Trim();
if (File.Exists(errPath))
{
//表示GD已失效
RestartProgram();
//第四步:删除err.log
File.Delete(errPath);
}
else
{
TimeSpan ts=new TimeSpan();
_currDateTime=DateTime.Now;
ts=_currDateTime-_startDateTime;
if(ts.Hours >=4)
{
RestartProgram();
}
}
}
private void RestartProgram()
{
//第一步:杀掉进程
KillProc("KeyVerify");
//第二步:重启进程
System.Diagnostics.Process.Start(_exePath);
System.Threading.Thread.Sleep(1000); //暂停1000秒
//第三步:触发按钮
//发送触发“启动验证”按钮的消息
int hwndKeyVerify = FindWindow(null, "验证");
IntPtr hwndPtr = new IntPtr(hwndKeyVerify);
IntPtr hwndButton = FindWindowEx(hwndPtr, (uint)0, "Button", "启动验证"); //获取目标程序的按钮启动验证的句柄
SetActiveWindow(hwndButton);
SetForegroundWindow(hwndButton); //将目标程序设为当前活动窗口
SendMessage(hwndButton, BM_CLICK, 0, 0);//模拟点击启动验证按钮
}
private void KillProc(string procName)
{
try
{
foreach (Process proc in Process.GetProcessesByName(procName))
{
if (!proc.CloseMainWindow())
{
proc.Kill();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
本文作者:网友 来源:网络
CIO之家 www.ciozj.com 微信公众号:imciow