Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

c# - Run a WPF Application as a Windows Service

We are developing a Windows Presentation Foundation Application that we would like to be able run as a Windows Service.

Anyone done something like that?
Is it possible?

We don't need to interact with the Desktop or any GUI, it would just be nice to have one App that we can run with a GUI, from the Command Line (that works) or as a Service.

Looking forward to interesting input :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As a rule of thumb services should never have any kind of UI. This is because services usually run with very high privileges and bad things can happen if you are not super careful with your inputs. (I think the newest versions of Windows won't let you create UI from a service at all but I am not 100% sure.)

If you need to communicate with a service, you should use some form of IPC (WCF, pipes, sockets, ...). If you want a simple console program that can also be a service, I know of a trick to set that up:

class MyExampleApp : ServiceBase
{
    public static void Main(string[] args)
    {
        if (args.Length == 1 && args[0].Equals("--console"))
        {
            new MyExampleApp().ConsoleRun();
        }
        else
        {
            ServiceBase.Run(new MyExampleApp());
        }
    }
    private void ConsoleRun()
    {
        Console.WriteLine(string.Format("{0}::starting...", GetType().FullName));

        OnStart(null);

        Console.WriteLine(string.Format("{0}::ready (ENTER to exit)", GetType().FullName));
        Console.ReadLine();

        OnStop();

        Console.WriteLine(string.Format("{0}::stopped", GetType().FullName));
    }
    //snip
}

If you just start the program, it will launch as a service (and yell at you if you run it from the console), but if you add the paramter --console when you start it, the program will launch and wait for you to hit enter to close.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...