开发者

How to show a form in windows service.

开发者 https://www.devze.com 2023-02-15 07:03 出处:网络
I want to load a form in OnStart() method in my windows service; here is my code. It is not working. Can you please provide any help ?

I want to load a form in OnStart() method in my windows service; here is my code. It is not working. Can you please provide any help ?

protected override void OnStart(string[] args)
{
    Form1 fr = new Form1();开发者_Go百科
    fr.Show();
}


You can't use services that way. Services can't interact with desktop directly, because they run in another WindowsStation from the logged in users session. You need to create another application that will communicate with your service.

How to make communication you can read on MSDN and in this example. Some ideas also described already on StackOverflow.


Services run in a different window station and desktop to any interactive user. Even if the form is loaded successfully nobody will be able to see it.

You can set the "Allow service to interact with desktop" service option which allows a service to share the console's window station. However, this is a really bad idea. It opens up security holes and a host of other problems. E.g. what happens if there is more than one user logged in? Or if you're running terminal services?

A more conventional design is to have a client application handling the UI and talking to the service running in the background.


GUI requires Single-Threaded Apartment threading model. Forms require a message pump (like the one started by Application.Run).

A service is definitely not designed to show GUI (even interactive services are considered bad practice), it can be controlled from a GUI, though.


For a service to display a window it has to be marked as "Allow interaction with desktop". This can be done by the service installer or on the property page for that service.

That's not enough to get the window to display reliably, though. In practice you will have to determine if there is a user currently logged in and get their desktop. This is not a trivial undertaking and can be a source of security issues. If there is no one currently logged in, you are out of luck.

The best solution is to have a separate GUI app which talks to the service via some IPC mechanism.

0

精彩评论

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

关注公众号