开发者

How to do things within a windows service?

I have an application, written by me in C#.net 2.0 - when the application is opened, a开发者_StackOverflow社区 timer will check every 3 seconds for x. If x happens, it shows a warning in a windows form.

Is there a possibility to install this timer and the windows form call in a windows-service? So that the timer ticks every time a system is up and shows the message then?


  1. No, it is not possible to have a service display a form. This is by design, since a service is supposed to run without a user interface
  2. You can have a regular application that communicates with your service and displays the warning, but I don't know how exactly this is done.
  3. IMO, you don't need a service, just create a regular application without a main form that runs in the background, performs your check, and displays a warning when necessary. You can add that application to the Run section of HKLM or HKCU, so that it is always started when a user logs on to the system.


Windows Forms cannot be displayed from a Windows Service. A Service runs only in the background.

You can have a separate Windows application that communicates with the Windows service and display warnings, information, etc.

To do this, the service runs on the LocalSystem account, and you have to enable the property for the service to interact with the desktop.


Services are forbidden from interacting with the desktop, including displaying windows or forms. In windows 2003 and XP you could work around the issue by marking the service 'interactive' and this would allow the service to display on the user session, but as of Windows 2008 and Vista this is enforced and services can no longer interact in any fashion with the user.

When services need to display anything, the solution is to split the logic into two separate processes, one being the service and one being a normal user process. The user process runs launched by the user, in its session (it can be launched automatically at session start up) and it connects to the service via some IPC channel (shared memory, named pipes, sockets etc). The service can then display anything it wishes to the user by asking the user process half of the application to display what it needs to display.


As others have said, remember that a windows service is supposed to be a background, never-interacting-with-the-user program. Many services run even when the user is not logged on -- how would they go about displaying a form when there's no desktop for them to display it on?

That said, it shounds like you're trying to shoehorn something into a service that shouldn't be a service. If you want something that runs in the background and still interacts with the user, look into making a lightweight system try application. In fact... here's a helpful tutorial:

Lightweight System Tray Application (NotifyIcon Based)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜