簡體   English   中英

從C#Windows Service使用GetWindowText

[英]Using GetWindowText from C# windows service

我有一個用C#(和Visual Studio 2013)編寫的Windows Service應用程序。

該服務使用計時器每秒檢查一次當前活動窗口,如果它是某個具有焦點的應用程序,則它將停止其他服務。

因此,這是獲取當前窗口名稱的代碼的主要部分:

[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的用戶?

有人知道我該如何解決嗎?

謝謝

服務在與用於交互式用戶的會話不同的會話(會話0)中運行。 Windows句柄是隔離的,這意味着服務無法從交互式用戶查詢窗口句柄。

從本質上講,您無法從服務過程中查詢此信息。 您將需要在與窗口相同的交互式桌面中運行查詢窗口的過程。 如果需要將信息重新提供給服務,則需要使用IPC機制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM