c# inter form and inter thread message passing method (main form receives sub form message, and sub form receives main form message)

Keywords: C#

Events are used to transfer messages between forms and threads

In C #, there is generally no need to customize delegates. The events given in C # are enough for us to use. Using this event well is the topic we will discuss below

1. Create a new event in the main form

Here are some definitions of an event.

 private event EventHandler RecEventHandler;

2. Create a new class

Create a new class to transfer messages between forms and threads. Define two attributes in the class (in this example, one is used to transfer IP address (remote) attribute and the other is used to transfer string (txt) attribute). You can also add more attributes to transfer messages, such as int shaping, floating point and other attributes. In this example, the author is used to transfer string messages (Note: this class inherits EventArgs)
Here are some examples of creating a new class.

#region creates a new class to pass the EventArgs parameter. This class is called by the event
    //Event call
    public class ReceiveEventAargs : EventArgs
    {
        public string remote { get; set; }
        public string txt { get; set; }
    }
    #endregion

3. Add a method for the event (this method triggers the event)

Here are some inline snippets.

 private void ReceiveEvent(string remote, string str)
 {
    if (remote != "")
   {
        if (RecEventHandler != null)
        {
            RecEventHandler(this, new ReceiveEventAargs() { remote = remote, txt = str });//Trigger event
        }
        
    }
  }

Note: new ReceiveEventAargs() is the class you created; this class inherits EventArgs. EventArgs is the base class

4. Add event receiving method in subform

AppendToText(remoteIP.remote, txt.txt) in the event receiving method; the method is to add data to the richtextBox rich text box and display it in the form.
Here are some inline snippets.

 internal void AppendEventHandler(Object sender, EventArgs e)
 {
      ClientEventAargs.ReceiveEventAargs remoteIP = e as ClientEventAargs.ReceiveEventAargs;
      ClientEventAargs.ReceiveEventAargs txt = e as ClientEventAargs.ReceiveEventAargs;
      //
      //The received message is displayed in the RichTextBox text box
      //
      AppendToText(remoteIP.remote, txt.txt);

  }

5. Subscription event

When initializing the subform, subscribe to the subform AppendEventHandler method. The initialized subform can appear anywhere in the program, depending on your own program needs. In this example, the author's subform appears in the form of user control (UC_MainWin) is a user control.
Here are some inline snippets.

UC_MainWin uC_MainWin = new();           
RecEventHandler += new EventHandler(uC_MainWin.AppendEventHandler);
uC_MainWin.Dock = DockStyle.Fill;

After completing these five steps, you can display the messages of other threads in the subform. If the base thread wants to call the message, you can do the opposite.

Event call

At this point, you can call the event. The following shows how to call this event (in this example, the author uses Socket receiving as an example, and the data received in Socket is multi-threaded message passing in this example)
Here are some inline snippets.

 public void ReciveData(object state)
 {
  //Baotou logo
  //
  string headTag = "";
  //
  //Total file length
  int fHeadInt = 0;
  //
  //Force conversion
  Socket client = state as Socket;
  //
  //
  if (client == null) return;
  //
  byte[] buffer = new byte[1024];//Define array size
  if (client != null && client.Connected) //The client object is not empty and the connection is true
  {
   while (PublicConst.jumpLoop)
   {
     if (!PublicConst.jumpLoop) return;     
      int len;
      try
      {
      	if ((len = client.Receive(buffer)) > 0)
        {
          //The RecevieByte method has culled the packet header. Data processing is performed in the class (AcceptData.RecevieByte)
          //
         byte[] receiveByte = AcceptData.RecevieByte(buffer, len, out headTag, out fHeadInt );
         switch (headTag)//Baotou logo
         {
           case "s"://Receive heartbeat packet
           if (receiveByte != null)
           {
             PublicConst.RecevieDataStr = System.Text.Encoding.UTF8.GetString(receiveByte, 0, receiveByte.Length);
             if (len > 0 && headTag == "s")//s is the client heartbeat packet
             {                                           
                 if (PublicConst.RecevieDataStr == "Client Information")
                 {
                     string remote = client.RemoteEndPoint.ToString();
                     //
                     //Receive event
                     //
                     ReceiveEvent(remote, PublicConst.RecevieDataStr);
                 }
             }
          }
            break;
        case "t"://Receive text box RTF content
             if (receiveByte != null)
             {
                 PublicConst.RecevieTextStr = System.Text.Encoding.UTF8.GetString(receiveByte, 0, receiveByte.Length);
                
                 string remote = client.RemoteEndPoint.ToString();
                 //
                 //Receive event
                 //
                 ReceiveEvent(remote, PublicConst.RecevieTextStr);
                 }
             break;
        case "m"://Receive picture file name
             if (receiveByte != null)
             {
                 PublicConst.RecevieImageFileName = System.Text.Encoding.UTF8.GetString(receiveByte, 0, receiveByte.Length);

             }
             break;
         case "i"://Receive picture
             if (receiveByte != null)
             {
                 
                 string floder = "Image";//Original folder
                 //Convert array to Image and save                       
                 SaveFileOrImage.BytesToImage(receiveByte, PublicConst.RecevieImageFileName, floder);
                
             }

             break;

         case "n"://Receive file name
             if (receiveByte != null)
             {
                 PublicConst.RecevieFileName = System.Text.Encoding.UTF8.GetString(receiveByte, 0, receiveByte.Length);

             }
			........
           break;                     
           default:
           break;
           }
       }

   }
     catch (Exception e)
      {
      
          string str = string.Format("Network exception: client exit{0}", e.Message);
          //
          //Receive event
          //
          ReceiveEvent(str);
          //
          return;
      }
  	}
  }
}
#endregion

Posted by theresandy on Sun, 19 Sep 2021 20:45:14 -0700