[英]Run windows application from Windows service
我創建了一個Windows應用程序,該應用程序應每次在桌面上運行。 為此,我們將應用程序啟動。 但是由於某些例外或關閉用戶窗口的應用程序越來越近。
為了避免這種情況,我已經編寫了Windows服務,它將每隔一分鍾檢查一次應用程序是否正在運行。 如果關閉,Windows服務將啟動應用程序。
當我調試Windows服務時,應用程序運行良好。 但是當我完成服務設置時。 服務每隔一分鍾運行一次,但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;
}
請任何人幫助您解決此問題。
嘗試看這個問題:
對於您的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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.