C# - Program without a Window

user646265 picture user646265 · Aug 26, 2011 · Viewed 10.2k times · Source

I'm wondering whether it is possible to 'turn off' my main Window from loading automatically when my program starts with a command-line argument (i.e. when a file name is passed). The problem I have is that my program loads when a file associated with it is clicked, but does so by opening another main window and using that. The problem I have is that the program still launches the MainWindow afterwards, thus opening two Windows, one with the file contents and one that is empty.

How do I prevent the blank Window? As I see it, I either stop it from opening the main Window, close the main Window or make the program pass the file to the main Window. My problem is that I don't know which of these would be the best or how to to do it.

This is the code:

    protected override void OnStartup(StartupEventArgs e)
    {
        if (e.Args != null && e.Args.Count() > 0)
        {
            this.Properties["ArbitraryArgName"] = e.Args[0];
        }
        base.OnStartup(e);

        if (Application.Current.Properties["ArbitraryArgName"] != null)
        {

            string fname = Application.Current.Properties["ArbitraryArgName"].ToString();
            MainWindow mw = new MainWindow();
            mw.Show();
            mw.readVcard(fname);
            Application.Current.Windows.
        }
    }

EDIT:

My solution is at the bottom.

Answer

Jon Skeet picture Jon Skeet · Aug 26, 2011

I believe you can add a separate class with its own Main method and set that to be the entry point of your executable. Then you can parse the method arguments there and either bring up the main window or not.

(I'm assuming this is a WPF app - it's simpler in a WinForms app as you can modify the original Main method directly.)