|
用C#写了一个定时监控服务,检测某一程序是否运行,如果没有运行,则启动改程序,如果已经运行,则不作任何操作。代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
namespace RegularMonitoringProgram
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
InitService();
}
private void InitService()
{
base.AutoLog = true;
base.CanShutdown = true;
base.CanStop = true;
base.CanPauseAndContinue = true;
base.ServiceName = "BMTService"; //这个名字很重要,设置不一致会产生 1083 错误哦!
}
protected override void OnStart(string[] args)
{
//timeExe 在Service1.Designer.cs 函数private void InitializeComponent()定义
this.timeExe.Enabled = true;
this.tCheckExe();
}
protected override void OnStop()
{
this.timeExe.Enabled = false;
}
//定时执行的事件
private void timeExe_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.tCheckExe();
}
private void tCheckExe()
{
Thread t = new Thread(new ThreadStart(OnTimedEvent));
t.Start();
}
private void OnTimedEvent()
{
bool InfoFlag = false;
string StartAppPath = "";
string ProcessName = "";
string flag = "";
string path = @"d:\Setting\setting.xml";
ProcessName = XMLSettings.getUrl("ProcessName", path);
StartAppPath = XMLSettings.getUrl("AppLocation", path);
flag = XMLSettings.getUrl("isUpdating", path);
Process[] Processes = Process.GetProcesses();
Process ProcessApp = Processes[0];
for (int i = 0; i < Processes.Length; i++)
{
if (Processes.ProcessName.ToLower() == ProcessName)
{
ProcessApp = Processes;
InfoFlag = true;
break;
}
else continue;
}
if (!InfoFlag)
{
if (flag=="0")
{
try
{
Process AppProcess = new Process();
AppProcess.StartInfo.FileName = StartAppPath;
//AppProcess.StartInfo.Arguments = "";
AppProcess.Start();
}
catch (Exception)
{
throw;
}
}
}
}
前台调试的时候可以出来用户程序界面,比如cmd.exe,就可以打开,但是裝到本地电脑服务之中就不显示前台界面了,求高手指点... |
|