Communicate between two windows forms in C#

后端 未结 12 1842
温柔的废话
温柔的废话 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:34

    The best way to deal with communication between containers is to implement an observer class

    The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. (Wikipedia)

    the way i do this is creating an Observer class, and inside it write something like this:

    1    public delegate void dlFuncToBeImplemented(string signal);
    2    public static event dlFuncToBeImplemented OnFuncToBeImplemented;
    3    public static void FuncToBeImplemented(string signal)
    4    {
    5         OnFuncToBeImplemented(signal);
    6    }
    

    so basically: the first line says that there would be a function that somebody else will implement

    the second line is creating an event that occurs when the delegated function will call

    and the third line is the creation of the function that calls the event

    so in your UserControl, you should add a function like this:

    private void ObserverRegister()//will contain all observer function registration
    {
        Observer.OnFuncToBeImplemented += Observer_OnFuncToBeImplemented;
        /*and more observer function registration............*/
    }
    
    
    void Observer_OnFuncToBeImplemented(string signal)//the function that will occur when  FuncToBeImplemented(signal) will call 
    {
        MessageBox.Show("Signal "+signal+" received!", "Atention!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
    

    and in your Form you should do something like:

    public static int signal = 0;
    
    public void button1_Click(object sender, EventArgs e)
    {
          Observer.FuncToBeImplemented(signal);//will call the event in the user control
    }
    

    and now, you can register this function to a whole bunch of other controls and containers and they will all get the signal

    I hope this would help :)

提交回复
热议问题