从Windows服务运行Windows应用程序

我创build了一个应该在桌面上运行的Windows应用程序。 为此,我们把应用程序启动。 但由于一些例外或用户closures窗口应用程序越来越近。

为了避免这种情况我写了windows服务,它会每隔一分钟检查应用程序是否正在运行。 如果closures,windows服务将启动应用程序。

当我debuggingWindows服务应用程序运行良好。 但是当我完成服务的设置。 服务每分钟运行一次,但windows应用程序没有打开。

代码如下:

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); } } 

检查实例的方法是否正在运行:

  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; } 

请任何人都可以帮助如何解决这个问题。

试着看这个问题:

Windows服务如何执行GUI应用程序?

在你的情况下,P / Invoke

不过如前所述,这是一个糟糕的设计选择。

必需的代码应该在使用SCM的服务中运行,并且任何所需的配置或者与服务的交互应该被放置在单独的客户端应用程序中,通过..任何你喜欢的方式进行通信。

这可以简单地通过:
1)创建一个控制台应用程序。
2)通过将输出类型作为Windows应用程序的属性来设置和部署控制台应用程序。

代码如下:

 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; }