如何以其他形式恢复计时器? [英] How to resume a timer in another form?
问题描述
我有 Form1
和 Form2
。
我在 Form1
中有计时器
,已命名计时器
。
现在,当用户点击 Form1中的暂停按钮时弹出/ code>,
Form2
,计时器暂停。
当用户在 Form2
上点击 button1
时, Form2
将关闭,计时器应继续运行,但现在我无法实现。
这是我到目前为止所尝试的:
On Form1
:
private void btnPause_Click( object sender,EventArgs e)
{
timer.Stop();
new Form2( this )。ShowDialog();
}
// 以及Form2可以调用的方法再次启动计时器
public void startTimer()
{
timer.Start();
}
和 Form2
:
<前lang =cs>表格f1;
Form1 form1 = new Form1();
public Form2(Form1 f)
{
this .f1 = f;
}
private void button1_Click( object sender,EventArgs e)
{
form1.startTimer();
this .Close();
}
我正在引用,因为 Form2上还有另一个按钮
单击时将关闭 Form2
和 Form1
并显示另一个表单。
我不确定我是否应该实际实例化 Form1
,但我似乎无法访问 startTimer()
通过 f1
。
解决此问题的最佳方法是什么?
- 不要将
Form1
的实例传递给Form2
。- 重写
btnPause_Click()
如下:
private void btnPause_Click(object sender,EventArgs e)
{
timer.Stop(); //停止计时器
new Form2()。ShowDialog(); //显示Form2并等待用户关闭它
timer.Start(); //重启计时器
}
/ ravi
I have Form1
and Form2
.
I have a Timer
in Form1
, named timer
.
Now, when the user clicks on the Pause button in Form1
, Form2
pops up, and the timer pauses.
When the user clicks on button1
on Form2
, Form2
will close and the timer is supposed to continue running, but right now I can't make it happen.
Here's what I've tried so far:
On Form1
:
private void btnPause_Click(object sender, EventArgs e)
{
timer.Stop();
new Form2(this).ShowDialog();
}
//and a method Form2 can call to start the timer again
public void startTimer()
{
timer.Start();
}
And on Form2
:
Form f1;
Form1 form1 = new Form1();
public Form2(Form1 f)
{
this.f1 = f;
}
private void button1_Click(object sender, EventArgs e)
{
form1.startTimer();
this.Close();
}
I'm referencing since there's also another button on Form2
that when clicked will close Form2
and Form1
and will show another form.
I'm not sure if I should actually instantiate Form1
, but I can't seem to access startTimer()
through f1
.
What would be the best approach to solve this?
- Don't pass an instance of
Form1
toForm2
.- Rewrite
btnPause_Click()
like so:
private void btnPause_Click(object sender, EventArgs e) { timer.Stop(); // stop the timer new Form2().ShowDialog(); // show Form2 and wait until the user closes it timer.Start(); // restart the timer }
/ravi
这篇关于如何以其他形式恢复计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!