Communicate between two windows forms in C#

后端 未结 12 1807
温柔的废话
温柔的废话 2020-11-21 04:40

I have two forms, one is the main form and the other is an options form. So say for example that the user clicks on my menu on the main form: Tools -> Options

12条回答
  •  花落未央
    2020-11-21 05:25

    There are lots of ways to perform communication between two Forms. Some of them have already been explained to you. I am showing you the other way around.

    Assuming you have to update some settings from the child form to the parent form. You can make use of these two ways as well :

    1. Using System.Action (Here you simply pass the main forms function as the parameter to the child form like a callback function)
    2. OpenForms Method ( You directly call one of your open forms)

    Using System.Action

    You can think of it as a callback function passed to the child form.

    // -------- IN THE MAIN FORM --------
    
    // CALLING THE CHILD FORM IN YOUR CODE LOOKS LIKE THIS
    Options frmOptions = new Options(UpdateSettings);
    frmOptions.Show();
    
    // YOUR FUNCTION IN THE MAIN FORM TO BE EXECUTED
    public void UpdateSettings(string data)
    {
       // DO YOUR STUFF HERE
    }
    
    // -------- IN THE CHILD FORM --------
    
    Action UpdateSettings = null;
    
    // IN THE CHILD FORMS CONSTRUCTOR
    public Options(Action UpdateSettings)
    {
        InitializeComponent();
        this.UpdateSettings = UpdateSettings;
    }
    
    private void btnUpdate_Click(object sender, EventArgs e)
    {
        // CALLING THE CALLBACK FUNCTION
        if (UpdateSettings != null)
            UpdateSettings("some data");
    }
    

    OpenForms Method

    This method is easy (2 lines). But only works with forms that are open. All you need to do is add these two lines where ever you want to pass some data.

    Main frmMain = (Main)Application.OpenForms["Main"];
    frmMain.UpdateSettings("Some data");
    

提交回复
热议问题