我有一个在表单1上运行的计时器,其中有一个名为“ timenumber”的标签显示了时间,我还有一个具有标签“ timer”的第二种表单。如何将它们链接在一起,使它们在同一时间具有相同的值。窗体1用作控制器,窗体2是在另一台监视器中显示的窗体。
答案 0 :(得分:1)
选项1
使用其构造函数将对Form1
中的倒数标签的引用传递给Form2
,然后使用此引用来订阅标签的TextChanged
事件:
在 Form1
中:
private int CountDown = 100;
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this.[The Counter Label]);
form2.Show();
this.timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
this.[The Counter Label].Text = CountDown.ToString();
if (CountDown == 0)
this.timer1.Enabled = false;
CountDown -= 1;
}
在 Form2
中:
public form2() : this(null) { }
public form2(Control timerCtl)
{
InitializeComponent();
if (timerCtl != null) {
timerCtl.TextChanged += (s, evt) => { this.[Some Label].Text = timerCtl.Text; };
}
}
选项2
使用可以设置为控件引用的Form2
公共属性。在创建Form1
的新实例之后,立即在Form2
中设置此属性。
但是,这意味着Form1
需要了解 Form2
中的此属性:
在 Form1
中:
private int CountDown = 100;
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
form2.CountDownControl = this.[The Counter Label];
this.timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
this.[The Counter Label].Text = CountDown.ToString();
if (CountDown == 0)
this.timer1.Enabled = false;
CountDown -= 1;
}
在 Form2
中:
private Control timerCtl = null;
public Control CountDownControl {
set { this.timerCtl = value;
if (value != null) {
this.timerCtl.TextChanged += (s, evt) => { this.[Some Label].Text = timerCtl.Text; };
}
}
}
还有许多其他选项。
您还可以在Form2
中使用公共属性,并直接在Timer.Tick
事件中设置此属性。如第二个示例所示,公共属性可以将其控件之一的Text属性设置为该属性的值。
我不太喜欢这个选项,尽管它可用。
在 Form1
中:
private int CountDown = 100;
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
this.timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
this.[The Counter Label].Text = CountDown.ToString();
form2?.CountDownValue = CountDown;
if (CountDown == 0)
this.timer1.Enabled = false;
CountDown -= 1;
}
在 Form2
中:
public int CountDownValue {
set { this.[Some Label].Text = value.ToString(); }
}
}
您还可以在Form1
中创建一个自定义事件,Form2
可以订阅或实现 INotifyPropertyChange
。但这是与Option1相同的东西。
答案 1 :(得分:0)
如果form1
打开form2
,这很容易。在Form2
中,定义一个属性以设置标签上的文本:
public string TimerText
{
set => _timerLabel.Text = value;
}
您可能还需要调用_timerLabel.Invalidate();
来强制刷新标签。
然后,当form1
中的倒数计时器更新时,只需在form2
中设置该属性:
private void Timer_Tick(object sender, EventArgs e)
{
// calculate remaining time
_form2.TimerText = remainingTime.ToString();
}
在这里,_form2
是对Form2
正在显示的form1
对象的引用。
您可以将Form2
中的属性设为int
或double
而不是string
;选择哪种选项取决于您是否对Form2
中的值进行其他操作。