Basically I need my application to run from system start until system shutdown. I figured out the following approach:
- create MyApp.exe and MyService.exe
- MyApp should install MyService as a service
- MyService is supposed to run at startup and periodically check if MyApp is running. If it’s not than start it.
That’s the code I wrote for my service:
protected override void OnStart(string[] args)
{
while(true)
{
int processesCount =
Process.GetProcessesByName(Settings.Default.MyAppName).Count() +
Process.GetProcessesByName(Settings.Default.MyAppName + ".vshost").Count() +
Process.GetProcessesByName(Settings.Default.MyAppUpdaterName).Count();
if(processesCount==0)
{
//restore
var p = new Process { StartInfo = { FileName = Settings.Default.MyAppName, Arguments = "" } };
p.Start();
}
else
{
}
System.Threading.Thread.Sleep(3000);
}
}
- How can I install this process so that it starts on windows start?
- I’m not sure if this infinite loop in OnStart method is a good idea. Is it?
- Is the general idea ok?
As Hans points out in comments this is hostile to the user and fortunately won’t work on Vista or later because services run in their own windows station. Put whatever logic you need to run all the time in the service and use an IPC mechanism such as WCF to communicate with an (optionally) running UI. If the user disables the service or exits the GUI respect their wishes…
Add an entry to
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunorHKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Runthat points to your GUI application.No. You need to return from
OnStartif you need to do work after OnStart returns create a Thread to do that work.