2

Very newbie question.

I want to overwrite the Main in my WPF app so if I double-click on a file, it will be loaded. My main function is:

    [STAThread]
    static void Main(string[] args)
    {
        FileConvert.App app = new FileConvert.App();
        app.InitializeComponent();

        if (args.Length > 0)
        {
            Window1 wnd1 = (Window1)(app.MainWindow);
            wnd1.SetProjectFile(args[0]);
        }

        app.Run();

My problem is that wnd1 is null. How do I get access to this window so I can pass it the filename to load?

Thanks!

1 Answer 1

5

Instead of overwriting the Main method, try overriding the OnStartup method in App.xaml.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        if (e.Args.Length > 0)
            ((Window1) MainWindow).SetProjectFile(e.Args[0]);
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

This won't compile, as args is not defined. More deeply, isn't args[0] going to be the name of the executable, not the first parameter?
@Steven StartupEventArgs.Args is different from args in Main(). Timwi's sample will work just fine (overlooking the fact that args[0] is a copy paste oversight).
@NVM: I'm guessing that what you're suggesting here is that, instead of args[0], they should be looking the value up in e.InitParams. If so, I'm not clear on what the key would be.
args[0] should be e.Args[0] is what I meant.
@Steven: As NVM has pointed out, I accidentally left args where I meant to change it to e.Args. More “deeply”, no, e.Args[0] (and args[0] in Main) is the first command-line argument. e.InitParams is only relevant for Silverlight plugins, not for desktop applications, and has nothing to do with the command line.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.