The effective way to communicate between the windows
In C#, communication between different windows (such as the main window and optional window) is critical to sharing data and promoting user interaction. For this reason, a variety of methods can be used from simple attributes to more complex technology.
A common method is to use attributes, define public attributes in the main window, and optional windows can set the values of these attributes. Although this method is simple and easy to understand, it will become cumbersome if it involves a large number of options.
Another more powerful method is to use the heavy -duty constructor. By creating a heavy -duty constructor in the optional window, the constructor uses the main window as a parameter, and you can create a direct reference between the windows. This quotation allows seamless communication and data exchange.
In order to explain this method, please consider the following implementation:
<code class="language-csharp">public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(this); frm.Show(); } public string LabelText { get { return Lbl.Text; } set { Lbl.Text = value; } } }</code>
In this example, Form1 uses the heavy load constructor function to call Form2, which transmits Form1's reference to Form2. In Form2, this reference is used to access and modify the attributes in Form1, which effectively realizes the data sharing between the two windows.
This Revised Response Maintautas the Original Image and ITS Format, RephraseS the Text for Improved Flow and Clarity, and user conCise Language While p Reserving the Original Meaning. The code exmples remain unchanged.<code class="language-csharp">public partial class Form2 : Form { public Form2() { InitializeComponent(); } private Form1 mainForm = null; public Form2(Form callingForm) { mainForm = callingForm as Form1; InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { this.mainForm.LabelText = txtMessage.Text; } }</code>
The above is the detailed content of How Can I Effectively Implement Inter-Form Communication in C#?. For more information, please follow other related articles on the PHP Chinese website!