Creating a WPF app with no interface (or WPF)

December 21, 2013

This does sound counter intuitive, but let’s have a look at an example. Let’s say that I want to create an application that, when called, created a text file with a list of its own arguments, and then finishes.

Console App?

So, the first thing you think is: create a console app. Good idea; here’s what it looks like:


    class Program
    {
        static void Main(string[] args)
        {            
            File.WriteAllLines("tmp.txt", args);
        }
    }

Okay, so it’s simple and it works. And here’s what it looks like when you run it:

Running Console App

It won’t say “Press any key” unless you run it with Ctrl-F5 (because you want to take a screenshot).

Anyway, as unobtrusive as that it, what if you didn’t want it to appear? Well, one option (and, as usual, I don’t claim this is the only option), you could create a WPF app instead. In the App.xaml, you can specify the start-up object… or not:


    
         
    

So, no StartupURI element. Next, you need to override the Startup event in App.Xaml.cs:


        protected override void OnStartup(StartupEventArgs e)
        {
            var args = e.Args.Select(a => a.ToString());
            File.WriteAllLines("tmp.txt", args);
            
            Shutdown();
        }

Conclusion

And that’s it… you now have a runable app that is completely devoid of a UI.

One word of warning: if this is going to be a slightly more complex app that makes use of asynchrony, then remember that you’re closing the app here.

As usual, if anyone knows of a better method of doing this then please leave a comment or get in touch.



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024