Introduction
Recently, I ran into a situation where I needed to make an application launch automatically on start up. The problem was that the program that I needed to launch was designed as a WinForms application. Therefore, the only way to make it launch automatically was to make the computer automatically login and run the application. Unfortunately, the company I was working for had a strict security policy, and forcing a computer to automatically login was out of the question.
Originally, I thought about converting the entire application to an NT service. However, I was on a tight deadline, and removing the UI code would have required some extensive work and additional testing. Therefore, I needed an alternative solution. After digging around on the internet for a while, I discovered the ProcessStartInfo
class. Suddenly, the light bulb turned on in my head, and I starting developing a new service which I have dubbed as the "Silent Process"...
Using the code
The code is very simple, and for the most part, self-explanatory. The service contains an OnStart
and an OnStop
method.
In the OnStart
method, I instantiate a new ProcessStartInfo
object. I then set the CreateNoWindow
property to true
. This way, I can run the WinForms application in the background. I also set the WindowStyle
property to Hidden
just as an extra precaution. The remaining properties are read from the app.config file. By modifying the configuration file, you can virtually make any application run as a service!
In the OnStop
method, I check for any processes that I may have launched. If I find any matching processes, I kill them.
protected override void OnStart(string[] args){
KillExistingProcesses();
try {
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.WorkingDirectory =
@ConfigurationSettings.AppSettings["working_directory"];
startInfo.FileName =
ConfigurationSettings.AppSettings["executable_name"];
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start( startInfo );
}
catch( Exception ex ) {
Console.WriteLine( ex.Message );
}
}
private void KillExistingProcesses(){
Process[] processes = Process.GetProcessesByName(
ConfigurationSettings.AppSettings["executable_name"].Replace(
".exe", String.Empty ) );
foreach( Process process in processes ) {
process.Kill();
}
}
protected override void OnStop(){
KillExistingProcesses();
}