WinForm中一个窗体调用另一个窗体的控件和事件的方法(附带源码)
时间: 2024-03-12 22:43:35 浏览: 565
可以使用委托(Delegate)和事件(Event)的方式实现。
首先,在被调用的窗体中定义一个委托和事件:
```csharp
public delegate void MyEventHandler(object sender, EventArgs e);
public event MyEventHandler MyEvent;
```
然后,在需要调用该事件的地方,调用该事件:
```csharp
MyEvent?.Invoke(this, EventArgs.Empty);
```
接着,在调用该事件的窗体中,在构造函数中订阅该事件:
```csharp
public Form1()
{
InitializeComponent();
form2.MyEvent += Form2_MyEvent;
}
```
在事件处理方法中,可以调用被调用窗体中的控件和方法:
```csharp
private void Form2_MyEvent(object sender, EventArgs e)
{
form2.textBox1.Text = "Hello, world!";
form2.button1.PerformClick();
}
```
下面是完整的源码示例:
被调用窗体 Form2 的代码:
```csharp
public partial class Form2 : Form
{
public delegate void MyEventHandler(object sender, EventArgs e);
public event MyEventHandler MyEvent;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyEvent?.Invoke(this, EventArgs.Empty);
}
}
```
调用窗体 Form1 的代码:
```csharp
public partial class Form1 : Form
{
private Form2 form2;
public Form1()
{
InitializeComponent();
form2 = new Form2();
form2.MyEvent += Form2_MyEvent;
}
private void button1_Click(object sender, EventArgs e)
{
form2.ShowDialog();
}
private void Form2_MyEvent(object sender, EventArgs e)
{
form2.textBox1.Text = "Hello, world!";
form2.button1.PerformClick();
}
}
```
阅读全文