我有两种形式,我使用以下方法创建第二种形式:
Form2 f2 = new Form2();
f2.Show();
Form2
有一个公共变量,并且每次鼠标移动都会更改。我在该表单上有一个按钮,按下时会保存变量。现在的问题是我不知道如何将其传递回Form1
。
答案 0 :(得分:1)
你应该使用事件。 Form2
应该定义一个适当触发的事件(听起来应该是单击按钮时)。然后Form1
可以订阅该事件并做任何事情。
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public event Action<string> MyEvent; //TODO give better name and set arguments for the Action
private void button1_Click(object sender, EventArgs e)
{
string someValue = "Hello World!"; //TODO get value that you want to share
if (MyEvent != null)
{
MyEvent(someValue);
}
}
}
然后以你的主要形式:
private void button1_Click(object sender, EventArgs e)
{
Form2 otherForm = new Form2();
//subscribe to the event. You could use a real method here, rather than an anonymous one, but I prefer doing it this way.
otherForm.MyEvent += value =>
{
//do other stuff with "value".
label1.Text = value;
};
otherForm.Show();
}