Today I have studied that in C #, cross-form call controls can be implemented without complicated methods such as custom messages. A better way for C # is to delegate.
Effect Description: there are two forms: FORM1 (A button control named "Open form2") and FORM2 (A button control named "Change form1 color ). At startup, click the button control "Open form2" in FORM1 to display FORM2. Click "Change form1 color" in FORM2 to change the color of Form1.
1. In Form2:
First declare a delegate and delegate instance
Out-of-class Form2
Public delegate void ChangeFormColor (bool topmost );
In Form2 class
Public event ChangeFormColor ChangeColor;
Call the delegate in the button event of Form2
Private void button#click (object sender, EventArgs e)
{
ChangeColor (true); // executes the delegated instance
}
Ii. In Form1:
The click event of the button control "Open form2" contains the following code:
{
Form2 f = new Form2 ();
F. ChangeColor + = new ChangeFormColor (f_ChangeColor );
F. Show ();
}
F. ChangeColor + = new ChangeFormColor (f_ChangeColor );
This sentence is the most critical. After you enter + =, press the Tab twice and it will automatically generate a callback function for you, as shown below:
Void f_ChangeColor (bool topmost)
{
This. BackColor = Color. LightBlue;
This. Text = "changed successfully ";
}
Iii. complete code
Using System;
Using System. Drawing;
Using System. Windows. Forms;
Namespace cross-form Call Control
{
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}
Private void button#click (object sender, EventArgs e)
{
Form2 f = new Form2 ();
F. ChangeColor + = new ChangeFormColor (f_ChangeColor );
F. Show ();
}
Void f_ChangeColor (bool topmost)
{
This. BackColor = Color. LightBlue;
This. Text = "changed successfully ";
}
}
}
Using System;
Using System. Windows. Forms;
Namespace cross-form Call Control
{
Public delegate void ChangeFormColor (bool topmost );
Public partial class Form2: Form
{
Public Form2 ()
{
InitializeComponent ();
}
Public event ChangeFormColor ChangeColor;
Private void button#click (object sender, EventArgs e)
{
ChangeColor (true); // executes the delegated instance
}
}
}
Finally, we will introduce you to the simplest C # Cross-form operation.
From tu jiankai's column