github地址:https://github.com/mzy666888/OneFormUpdateOtherForm
1、新建一个winform的工程,名称为:TwoFormUpdate
新添加一个Form2。在Form2中添加一个label,并将label的Modifiers更改为public,
在Form1中添加三个按钮,名称分别为:显示窗体,开始,结束 ,定义的变量和三个按钮的点击事件如下实现:
namespace TwoFormUpdate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool isRun = true;
private Form2 form2;
/// <summary>
/// 开始按钮点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//rm2.Show();
isRun = true;
Random rd = new Random();
Task.Run(
() =>
{
while (isRun)
{
form2.Invoke(new Action<int>(
(args) => { form2.label1.Text = $"当前值:{args}"; }), rd.Next());
Thread.Sleep(10);
}
});
}
/// <summary>
/// 显示窗体点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
form2 = new Form2();
form2.Show();
}
/// <summary>
/// 结束按钮点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
isRun = false;
}
}
}
2、效果运行图