Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling public method on windows form after application.run

Tags:

c#

winforms

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());
    }
}
like image 467
geoff swartz Avatar asked May 24 '12 13:05

geoff swartz


1 Answers

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();
}
like image 127
IAbstract Avatar answered Sep 24 '22 03:09

IAbstract