Appleoddity
Appleoddity

Reputation: 1171

Call function in instance of class from a sub-form in C#

I'm sure this is really simple, but I just can't find the right phrase to google.

I have an application that is meant to be a tray application.

The Main() function initializes an instance of a class CustomApplicationContext:

 private static void Main()
{
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);
  Application.Run(new CustomApplicationContext());
}

Within this class, I have a function:

public void DoRestart()
{

  if (_DoRestartDialog == null)
  {
    using (_DoRestartDialog = new RestartDialog())
      _DoRestartDialog.ShowDialog();
      _DoRestartDialog = null;
  }
  else
    _DoRestartDialog.Activate();
}

I also have a function in this class that opens a form:

protected override void OnTrayIconDoubleClick(MouseEventArgs e)
{
  if (e.Button == MouseButtons.Left)
  {
            if (_InfoDialog == null)
            {
                using (_InfoDialog = new InfoDialog())
                    _InfoDialog.ShowDialog();
                _InfoDialog = null;
            }
            else
                _InfoDialog.Activate();
           
  }

  base.OnTrayIconDoubleClick(e);
}

Within the form is a button. When the button is clicked I want to call the DoRestart function in the primary class. How do I reference this function? I can't seem to get access to it from the form.

Upvotes: 2

Views: 110

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39132

Instead of passing your instance directly to Run(), store it at class level first:

public static CustomApplicationContext App;

private static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    App = new CustomApplicationContext();
    Application.Run(App);
}

Now you can access it with:

Program.App.DoRestart();

Upvotes: 3

Related Questions