Run windows application from Windows service
This can be achieved simply by:
1)creating one console application.
2)Setup and deployment of Console application by making Output type as Windows Application from properties.
Code as follows:
static void Main(string[] args)
{
Timer t = new Timer(callback, null, 0, 60000);
Thread.Sleep(System.Threading.Timeout.Infinite);
}
// This method's signature must match the TimerCallback delegate
private static void callback(Object state)
{
try
{
bool isAppRunning = IsProcessOpen("APPName");
if (!isAppRunning)
{
Process p = new Process();
string strAppPath;
strAppPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + @"\FolderName\AppName.exe";
System.Diagnostics.Process.Start(strAppPath);
}
}
catch
{ }
}
public static bool IsProcessOpen(string name)
{
//here we're going to get a list of all running processes on
//the computer
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains(name))
{
//if the process is found to be running then we
//return a true
return true;
}
}
//otherwise we return a false
return false;
}
Hussain
Updated on June 04, 2022Comments
-
Hussain almost 2 years
I have created one windows application which should run every time in the desktop. For this we put the application in startup. But due to some exceptions or user closing the window application getting close.
To avoid this I had written windows service, it will check every one minute whether application is running or not. If it is closed windows service will start the application.
When i am debugging the windows service the application is running fine. But when i done setup of the service. Service is running every one minute but windows application is not opening.
code as follows:
void serviceTimer_Elapsed(object sender, EventArgs e) { try { bool isAppRunning = IsProcessOpen("App"); if (!isAppRunning) { Process p = new Process(); if (Environment.Is64BitOperatingSystem) p.StartInfo.FileName = @"C:\Program Files (x86)\Creative Solutions\App\App.exe"; else p.StartInfo.FileName = @"C:\Program Files\Creative Solutions\App\App.exe"; p.Start(); } } catch (Exception ex) { WriteErrorLog("Error in service " + ex.Message); } }
Method to check instance is running or not:
public bool IsProcessOpen(string name) { //here we're going to get a list of all running processes on //the computer foreach (Process clsProcess in Process.GetProcesses()) { if (clsProcess.ProcessName.Contains(name)) { //if the process is found to be running then we //return a true return true; } } //otherwise we return a false return false; }
Please can anyone help how to resolve this issue.