geoff swartz
geoff swartz

Reputation: 5977

calling public method on windows form after application.run

I have a windows form that will usually be running as a scheduled task so my thinking was that I would pass in command arguments in the task to make it run automatically. That way I could run it locally without arguments to manually run it if necessary. But I'm not quite sure how to make it call the method of the new form after calling Application.Run when it runs as a task. Right now it's just showing the form and exiting there instead of then continuing on to the i.RunImport() line. Any ideas? Here's my code. Thanks.

static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    if (args.Length > 0)
    {
        if (args.Any(x => x == "run=1"))
        {
            var i = new Importer();
            Application.Run(i);
            i.RunImport();
        }
    }
    else
    {
        Application.Run(new Importer());
    }
}

Upvotes: 6

Views: 3214

Answers (1)

IAbstract
IAbstract

Reputation: 19881

Write an event handler for the Form.Load event:

static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    if (args.Length > 0)
    {
        if (args.Any(x => x == "run=1"))
        {
            var i = new Importer();
            // modify here
            i.Load += ImporterLoaded;
            Application.Run(i);

            // unsubscribe
            i.Load -= ImporterLoaded;
      }
    }
    else
    {
        Application.Run(new Importer());
    }
}

static void ImporterLoaded(object sender, EventArgs){
   (sender as Importer).RunImport();
}

Upvotes: 7

Related Questions