开发者

How to call a function in a settings form from my main form?

开发者 https://www.devze.com 2023-04-05 13:24 出处:网络
I have two forms in my project, Main Form Settings form I need to call a method from the main form for an event in 开发者_StackOverflow中文版the settings form. My main form has the splash screen (

I have two forms in my project,

  1. Main Form
  2. Settings form

I need to call a method from the main form for an event in 开发者_StackOverflow中文版the settings form. My main form has the splash screen (in the constructor) so I could not create an instance of the main form to call the method.

Is there any way to call the function without calling the main form's constructor? Or is there any other way I can implement this?


You can send the Main form to the Settings form as a constructor argument (assuming Settings is called from Main).

A better method would be to send a Func<...> or Action<...> to the Settings form and let it call that instead.

...

public Settings(Action<int> myAction)
{  
    _myAction = myAction;
}


...
    _myAction(5);

...


You could setup a singleton class that holds your common functions that you need to call from your forms.

Some info on Singletons in c# http://msdn.microsoft.com/en-us/library/ff650316.aspx


In your Main Form keep the reference to the instance of SettingForm.

SettingsForm mySettingsForm;

public MainForm(SettingsForm settingsForm)
{
    _mySettingsForm = settingsForm;
}

private void CallSettingsFormMethods()
{
   _mySettingsForm.CallAnyPublicMethod();
}

When creating the MainForm instance, create an instance of SettingsForm and pass it to the MainForm. SettingsForm won't be visible unless you call Show or ShowDialog methods.

SettingsForm settingsForm = new SettingsForm();
MainForm myMainForm = new MainForm(settingsForm);
myMainForm.Show();
0

精彩评论

暂无评论...
验证码 换一张
取 消