Reputation: 4708
I have a Windows Service application written in C# (and Visual Studio 2013).
The service checks the current active window every second using a timer and if it's a certain application that has focus it then stops a different service.
So, here is the main part of my code that gets the current window name:
[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();
}
So I then check if current window matches a value that I save in the app.config.
If it does then I stop the service, else I start it.
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();
}
}
This all works when I test the application from Visual Studio using a launcher application. But once I install the service it doesn't work correctly.
The reason is because the windowName variable is empty. I guess this is because the service can't access the users running windows?
Do anyone know how I can get round this?
Thanks
Upvotes: 1
Views: 2062
Reputation: 612794
Services run in a different session (session 0), from the sessions used for interactive users. Windows handles are isolated and this means that a service cannot query a window handle from an interactive user.
Essentially there is no way for you to query this information from the service process. You will need to run the process that queries the window in the same interactive desktop as the window. If you need to get the information back to the service then you'll need to use an IPC mechanism.
Upvotes: 2