Home >Backend Development >C++ >How to Efficiently Communicate Between Two Windows Forms in C#?
The communication between the two Windows windows in C#
The method of heavy load constructor
In the main window, define a constructor, which uses the instance of the option window as the parameter:
<code class="language-csharp">public partial class Form1 : Form { public Form1() { InitializeComponent(); } public Form1(Form2 optionsForm) { InitializeComponent(); // 根据optionsForm参数初始化必要的选项 } // ... 其他代码 }</code>In the optional window, define a heavy -duty constructor, which accepts the main window:
<code class="language-csharp">public partial class Form2 : Form { private Form1 _mainForm; public Form2() { InitializeComponent(); } public Form2(Form1 mainForm) { InitializeComponent(); _mainForm = mainForm; } // ... 其他代码 }</code>When the optional window is opened from the main window, the instance of the main window is passed as a parameter to the constructor of the option window:
<code class="language-csharp">private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(this); frm.Show(); }</code>In the optional window, you can now access the attributes and methods of directly accessing the main window through _mainform. For example, you can modify the label on the main window:
<code class="language-csharp">private void button1_Click(object sender, EventArgs e) { _mainForm.label1.Text = "从选项窗体修改"; }</code>This method provides a simple and effective way to communicate data between windows without relying on complex attribute management. It is particularly useful for the optional window or dialog box that needs to transmit multiple data point transmission windows.
The above is the detailed content of How to Efficiently Communicate Between Two Windows Forms in C#?. For more information, please follow other related articles on the PHP Chinese website!