功能:
每三十分鐘掃描進程,若是不存在進程fromdemo.exe.則啓動該應用程序.
1.檢測進程進否存在
代碼
///
<summary>
///檢查進程是否已啓動
///
</summary>
///
<param name="processName"></param>
///
<returns></returns>
private static bool IsExistProcess(string processName)
{
Process[] MyProcesses = Process.GetProcessesByName(processName);
if (MyProcesses != null && MyProcesses.Length > 0)
{
return true;
}
return false;
}
2.建一個windows services 工程,添加一個System.Timers.Timer來使用.
// Create a timer with a 60*5 second interval.
aTimer = new System.Timers.Timer(60000*30);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
在OnTimedEvent裏寫要處理的內容.
代碼if(!IsExistProcess("FormDemo"))
{
Process p=
newProcess();
stringlocation=System.Reflection.Assembly.GetExecutingAssembly().Location;
stringdir=location.Substring(0, location.LastIndexOf("\\")+
1);
p.StartInfo.FileName=dir+
"FormDemo.exe";
p.Start();
}
}
3.添加安裝程序.我使用localsystem使用戶,自動啓動
在ServiceProcessInstaller的onCommited事件裏設置服務能夠與桌面交互,不然會看不到界面,雖然進程裏面會有.
代碼
//容許桌面交互
private
voidserviceProcessInstaller_Committed(objectsender, InstallEventArgs e)
{
try
{
ConnectionOptions myConOptions=
newConnectionOptions();
myConOptions.Impersonation=ImpersonationLevel.Impersonate;
ManagementScope mgmtScope=
newSystem.Management.ManagementScope(@"root\CIMV2", myConOptions);
mgmtScope.Connect();
ManagementObject wmiService=
newManagementObject("Win32_Service.Name='"
+serviceInstaller.ServiceName+
"'");
ManagementBaseObject InParam=wmiService.GetMethodParameters("Change");
InParam["DesktopInteract"]=
true;
ManagementBaseObject OutParam=wmiService.InvokeMethod("Change", InParam,null);
#regionWindows服務安裝後自動啓動
Process p=
newProcess();
p.StartInfo.FileName=
"cmd.exe";
p.StartInfo.UseShellExecute=
false;
p.StartInfo.RedirectStandardInput=
true;
p.StartInfo.RedirectStandardOutput=
true;
p.StartInfo.RedirectStandardError=
true;
p.StartInfo.CreateNoWindow=
true;
p.Start();
stringCmdstring=
"net start"
+serviceInstaller.ServiceName;
p.StandardInput.WriteLine(Cmdstring);
p.StandardInput.WriteLine("exit");
#endregion
}
catch
{
EventLog.WriteEvent("test failer",null,null,null);
}
}
第一次我使用安裝項目進行安裝,沒有順利進行,後來改成批處理了,直接把對應版本的installutil.exe拷由到服務所在路徑,而後
installutil /i myservice.exe
net start myservice
pauseweb