NEWS

Tuesday, September 4, 2012

Calling an exe from Windows Service


Some times we may need to call an exe from our windows service program. The following code can be used to call an exe from an appication. The sample code is for VB.NET applications. Here the calculator (calc.exe) is called.

Dim startInfo As System.Diagnostics.ProcessStartInfo

Dim pStart As New System.Diagnostics.Process
'Start the process
startInfo = New System.Diagnostics.ProcessStartInfo("calc.exe")
pStart.StartInfo = startInfo
pStart.Start()
pStart.WaitForExit()
pStart.Close()
Here
pStart.WaitForExit() makes your application wait till the called exe is closed.
pStart.Close() will free all the resources that are associated with this component.
This will work if you are using a windows Application. But in a windows service this will not work straight, you need to change some setting for the windows service. A service won't be able to show the GUI of an application, so if the application you are calling has any GUI you won't be able to see it. But the process will get kicked off and you can see the evidence in TaskManager. But we can enable the service to popup the UI by enabling this settings.
Allow Services to interact with desktop
  1. Start -> Run -> Services.msc
  2. Locate the services which you have created
  3. Right click and select properties.
  4. Select "Log On" tab on the top of the screen
  5. Select "Allow Services to interact with desktop" check box.
  6. Click on "Apply" and start the services.
If you want to kill an application during Windows Service Stop, try the following code
Dim myProcess As Process
Dim myProcesses As Process() = Process.GetProcessesByName("calc")
For Each myProcess In myProcesses
myProcess.Kill()
Next