我有用C#(和Visual Studio 2013)編寫的Windows服務應用程序。從C#窗口服務使用GetWindowText
服務使用定時器每秒鐘檢查當前活動窗口,如果它是某個具有焦點的應用程序,則會停止其他服務。
所以,這裏是獲取當前窗口的名字我的代碼的主要部分:
[DllImport("user32.dll")]
static extern int GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(int hWnd, StringBuilder text, int count);
const int nChars = 256;
int handle = 0;
StringBuilder Buff = new StringBuilder(nChars);
string windowName = String.Empty;
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
windowName = Buff.ToString();
}
所以我再檢查,如果當前窗口,我救在App.config的值相匹配。
如果確實如此,我會停止服務,否則我會啓動它。
ServiceController service = new ServiceController("SomeServiceName");
if (windowName.ToUpper() == ConfigurationManager.AppSettings["ApplicationTitle"].ToUpper())
{
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
}
}
else
{
if (service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
}
}
這一切都適用於我使用啓動程序從Visual Studio測試應用程序。但是,一旦我安裝了服務,它不能正常工作。
原因是因爲windowName變量爲空。我想這是因爲該服務無法訪問運行Windows的用戶?
有誰知道我可以如何解決這個問題?
謝謝
如果您控制Windows程序以及服務,則可以讓Windows程序在前臺設置事件,並在事件不再是前臺窗口時清除事件。該服務然後可以查詢該事件的狀態。 –
我不能這樣做,因爲它是一個Windows應用商店應用程序,我無法訪問這些服務。 – Sun