tags:

views:

46

answers:

1

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!

+4  A: 

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]);
    }
}
Timwi
interesting... thanks!
380380
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 Sudit
@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
@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.
Steven Sudit
args[0] should be e.Args[0] is what I meant.
NVM
@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.
Timwi
@NVM and @Timwi: It looks like I googled up the *wrong* version of StartupEventArgs; the Silverlight one. The code as it currently stands, with `e.Args`, looks correct.
Steven Sudit