The communication between the two Windows windows in C#
In the C#application, communication between multiple windows is essential for data exchange and coordination. This article will discuss a common scenario: transmit data from the option window to the main window. Although the use of attributes is a feasible method, it may become very cumbersome for a large number of options.
The method of heavy load constructor
A more effective solution is to use the heavy -duty constructor. The following is its working principle:
In the main window, define a constructor, which uses the instance of the option window as the parameter:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Form1(Form2 optionsForm)
{
InitializeComponent();
// 根据optionsForm参数初始化必要的选项
}
// ... 其他代码
}
Copy after login
In the optional window, define a heavy -duty constructor, which accepts the main window:
public partial class Form2 : Form
{
private Form1 _mainForm;
public Form2()
{
InitializeComponent();
}
public Form2(Form1 mainForm)
{
InitializeComponent();
_mainForm = mainForm;
}
// ... 其他代码
}
Copy after login
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:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
Copy after login
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:
private void button1_Click(object sender, EventArgs e)
{
_mainForm.label1.Text = "从选项窗体修改";
}
Copy after login
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!