TL;DR: I have a service, a gui, and a tray icon. I want to know how to get the tray icon to run on user login/start-up and be able to stop the service and start the gui
Some Background Info:
I have a windows service I've made that uses a xml file to collect
files from other computers on my network and store them on the local
pc (running the service). the xml has some structures called
'profiles' which have info like FileDestination, LocationToTakeFrom,
FileTypeToTake, and IsProfileActive...
The service basically takes all the active profiles and every hour
scans the location for files created within a 1hr window of the
current date/time on local PC.
My GUI allows the user to make profiles / modify profiles, as
well as determine which profile(s) should be active for collection. I
dont want this gui running at all times, so I plan to have a
systemTrayIcon to allow this GUI to be opened and shutdown.
I'm using Visual Studio 2010 .NET 4.0 everything is in C#, I have 1 solution with separate projects(gui and service)
I'm wondering about the following things as far as the System Tray Icon goes:
1) how do I have the icon start on user login (note that this will be distributed via an installer, not just my personal use. so It has to be done via code)
2) Stop a service via sysTrayIcon
3) where to place the SysTrayIcon... do I make a 3rd project? add it in the GUI project? not quite sure here.
4) if SysTrayIcon IS in a seperate project how can I have it create instances of the GUI?
ie how can I start the GUI application from code in a different project
the project requirements are:
-upon installation the GUI must start, after that the Gui should only be accessed through the tray icon.
-user should be able to stop the service any time via system tray icon
Start the client
There are plenty of ways to start an application on Login under Windows. Just grab SysInternals AutoRuns to get an idea. The obvious ones are (a) the good ol' Startup group and (b) one of the
\SOFTWARE\Microsoft\Windows\CurrentVersion\Run*
keys under HKCU and/or HKLM. That's the typical task of an setup utility, which makes sense since you have to install the service anyway. To do it in code:
Registry: Open the reg key, add the entry, close the reg key.
Startup: determine the value of CSIDL_STARTUP or CSIDL_COMMON_STARTUP using SHGetFolderPath, then create a Shell Link in that folder.
Service communication & control
The GUI part implements the TrayIcon and communicates through some channnel with your service. Again, there are plenty of possibilities how to do this, like disk files or memory mapped files, named pipes, even sockets. It would be too broad to list all the ways here, so I'd suggest to decide for one way and ask again if you have specific questions on that one.
To stop your service from code, use the ControlService() function and pass SERVICE_CONTROL_STOP as the dwControl parameter. To start a service, there's another function named (big surprise) StartService() to achieve that. Note that you may need to start an elevated copy of your app to control services. A quick & dirty way is to simply launch net start/stop MyService elevated with the necessary args.
Related
For the record, I want to point out two things:
I know how to create a Windows Service, I know how to create Tray applications and how to communicate with my Windows Service
I have read countless articles on this subject, almost all of them suggest hacks, putting applications in the Startup menu, (old) interactive desktop services, startup scripts etc. I also found very resources for the subject dated after 2010 (aka light years in the world of technology)
What I'm looking for is the proper way to make sure that when my service is installed, every user gets a nice icon in his tray whenever he/she logs on to his/her computer. This is slightly more complex than it seems, and most of the hackish solutions won't work anyway (not that I'd want to use them anyway).
What I want to achieve is twofold. I want to know how to:
Start the Tray application WITHOUT modifying any user settings. This means not adding anything to the user startup, not modifying the registry, no startup-scripts or whatever. My company doesn't have fixed seats in almost all of its departments. Any user can log on to nearly every workstation at every time. Ideally the Tray application would be launched from the service detecting a user logging on or the shell being started, and then spawning an instance of the tray application for that user.
I'm also looking for a way to handle the startup of the service. For example, when I start up the service and multiple users are logged on to a single machine (which is entirely possible), the service should spawn a tray application instance for each of the users with an interactive logon. This is especially important should the service need to recover. The same goes for when the service is stopped or restarted.
Just to give you an idea, the application I'm writing consists out of a Windows Service, a Tray application that gives feedback to users via notifications and allows them to start op a configuration program that also contains additional information for them, and finally said configuration program that communicates with the service via named pipes. It's all very simple.
I’m working on a windows app composed of two parts:
An agent, running in the background.
A main application with a window to start/stop the agent and configure it.
What I understand is that I should use a “windows service” for the agent.
But I’m not sure how this is supposed to be packaged? (Can I have these two parts in the same .exe?)
And how the agent and the main application can communicate (should I use a shared file? Can my agent have a private folder to work in?)
I’m looking for some architecture advices basically
Running the agent as a service is probably the best way to go. It'll run without anyone needing to be logged in to run it, and Windows provides extensive monitoring support for services. You can use the sc command to install, start and stop a service, and it even supports controlling services on other machines if you've got the appropriate permissions.
In order to have your gui communicate with it you could look at using WCF. It will allow you to define your interactions with the service as C# classes and will save you having to worry about checking shared directories or looking into a shared file etc. This approach will also make it easy to support multiple clients at the same time, whilst something like a shared folder approach will make this difficult.
You will need to have to separate .exe files, one for the service and one for the windows application. You can package these are two separate MSIs within Visual Studio, the benefit here is that if you need to move the service (for whatever reason) you are not then also packaging up the Windows App and leaving it where ever you install the service.
There are different ways you can have them communicate without getting massively complex. you could read from a text file, as you've suggested, but this could cause locking problems. When I've had to do similar I created a simple database in SQL (or any brand of database you wish), and have the Windows App insert / update configuration options to a table, and the service then reads the table to get its settings.
I have written a Windows service that allows me to remotely run and stop applications. These applications are run using CreateProcess, and this works for me because most of them only perform backend processing. Recently, I need to run applications that present GUI to the current log in user. How do I code in C++ to allow my service to locate the currently active desktop and run the GUI on it?
Roger Lipscombe's answer, to use WTSEnumerateSessions to find the right desktop, then CreateProcessAsUser to start the application on that desktop (you pass it the handle of the desktop as part of the STARTUPINFO structure) is correct.
However, I would strongly recommend against doing this. In some environments, such as Terminal Server hosts with many active users, determining which desktop is the 'active' one isn't easy, and may not even be possible.
But most importantly, if an application will suddenly appear on a user's desktop, this may very well occur at a bad time (either because the user simply isn't expecting it, or because you're trying to launch the app when the session isn't quite initialized yet, in the process of shutting down, or whatever).
A more conventional approach would be to put a shortcut to a small client app for your service in the global startup group. This app will then launch along with every user session, and can be used start other apps (if so desired) without any juggling of user credentials, sessions and/or desktops.
Also, this shortcut can be moved/disabled by administrators as desired, which will make deployment of your application much easier, since it doesn't deviate from the standards used by other Windows apps...
The short answer is "You don't", as opening a GUI program running under another user context is a security vulnerability commonly known as a Shatter Attack.
Take a look at this MSDN article: Interactive Services. It gives some options for a service to interact with a user.
In short you have these options:
Display a dialog box in the user's session using the WTSSendMessage function.
Create a separate hidden GUI application and use the CreateProcessAsUser function to run the application within the context of the interactive user. Design the GUI application to communicate with the service through some method of interprocess communication (IPC), for example, named pipes. The service communicates with the GUI application to tell it when to display the GUI. The application communicates the results of the user interaction back to the service so that the service can take the appropriate action. Note that IPC can expose your service interfaces over the network unless you use an appropriate access control list (ACL).
If this service runs on a multiuser system, add the application to the following key so that it is run in each session: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run. If the application uses named pipes for IPC, the server can distinguish between multiple user processes by giving each pipe a unique name based on the session ID.
WTSEnumerateSessions and CreateProcessAsUser.
Several people suggested WTSEnumerateSessions and CreateProcessAsUser. I wonder why no one suggested WTSGetActiveConsoleSessionId, since you said you only want to target one logged in user.
Several people sure are right to suggest CreateProcessAsUser though. If you call plain old CreateProcess the way you said, then the application's GUI will run with your service's privileges instead of the user's privileges.
That problems Session 0 , Interactive Services ,
Windows Service Allow Service To Interact With Desktop
on Windows 7 or Windows Vista
You can read this article
http://www.codeproject.com/KB/vista-security/SubvertingVistaUAC.aspx
I try explained here it's working on Windows 7
On Win2K, XP and Win2K3 the console user is logged on in Session 0, the same session the services live in. If a service is configured as interactive, it'll be able to show the UI on the user's desktop.
However, on Vista, no user can be logged on in Session 0. Showing UI from a service there is a bit trickier. You need to enumerate the active sessions using WTSEnumerateSessions API, find the console session and create the process as that user. Of course, you need also a token or user credentials to be able to do that. You can read more details about this process here.
I think as long as you have only one user logged in, it will automatically display on that user's desktop.
Anyway, be very careful when having a service start an exe.
If the write access to the folder with the exe is not restricted, any user can replace that exe with any other program, which will then be run with sytem rights. Take for example cmd.exe (available on all windows sytems). The next time the service tries to start your exe, you get a command shell with system rights...
If you launch a GUI from your service it will show up on the currently active desktop.
But only if you adjusted the service permissions: You need to allow it to interact with the desktop.
Important Services cannot directly interact with a user as of Windows Vista. Therefore, the techniques mentioned in the section titled Using an Interactive Service should not be used in new code.
This is taken from : http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx
I am writing a windows service to process emails on a daily basis. This service includes a App.Config file, which has several parameters for the service to work accordingly.
Every time, the admin user has to go and change / add / delete the pair inside the section using a text editor.
I am planning to include a windows form to load all the pair from the section and thinking of doing any modification through the form.
All I would like to know is whether it's possible to have a winform inside a windows service and open it when ever the configuration needs to be changed? I know we can have a seperated windows application and load the App.Config file of the windows service. I just want to avoid having a seperate app for this.
If you have done something very similar to this, please share your thoughts!
Regards,
Sriram
That sounds like a security issue if nothing else.
A Windows service runs in a different context and account and cannot interact with the desktop unless specifically allowed when installing the service. This is not enough of course so you'd also have to have the service running under the same account that is running the desktop - this in itself is really bad design and not something I would recommend.
You could also have the service executable decide what to do during launch, a common pattern is to have it spawn as a console application when debugging to simplify development. But then you'd have to stop the service and launch the service executable manually interactively to get the UI behaviour.
In any way, a separate configuration tool is the way to go.
I have a Windows service which I want to periodically execute an external program. I'm currently doing this the usual way
Process program = Process.Start(#"C:\mpewatch\db_parameters\DBParameters.exe");
This doesn't seem to be working. I'm executing this from a separate thread which is started in my service's OnStart handler. Is there any conceptual problem with this? Is it not possible to execute external programs from a service like this?
You can execute external programs from a service, but there are security issues. For example, your service may be running under an account which does not have read access to the folder where the external program resides, even if your interactive account does have that access.
For test purposes, try to configure the service to run under your interactive account. If the program is invoked as expected, then the problem with the original account is that it does not have sufficient privileges to run the program.
Your question didn't indicate the operating system.
On Windows XP, you can configure your Windows service to interact with the desktop by opening the service control panel, double-clicking your service, selecting the Log On tab, configuring the service to run as local system, and checking the checkbox. It's pretty straightforward. You might try testing with something like Notepad.exe just to see if you can get it working.
On Vista (and presumably Windows 7), however, you may be out of luck. I have read that the ability for Windows services to interact with the desktop has been removed in Vista. I forget what the terminology is, but basically services will run in "shell 0," whereas users will occupy "shell 1". User applications will be able to communicate with services and vice versa using technology like WCF, but services will not be able to communicate directly with the desktop. For example, any error boxes that pop up will have to be dealt with by swapping to "shell 0." Again, this is based on something I read a few months ago, and I haven't gone looking at it again. For me, I've structured my Windows service to be configured using WCF via a front-end app.
I'm sorry I don't have a link for you, but if your service will eventually have to migrate to a newer OS (or you are already there), this is something to check on.
Another critical consideration with Windows Services is that there is no GUI. Technically, there is an option to allow the service to interact with a local GUI, but you will not see it. This is due to services running as the Local System user.
Within a service, any modal dialog box (OK, Cancel, etc) is considered an error.