我有一个计时器在我的 form1 上运行,我希望当我点击 form2 的按钮时它会停止。我该怎么做。任何人都在这里寻求帮助。是定时器启动码。
//timer1.Start();
//picboxstart.Image = Resources.puse;
panelwork.BackColor = Color.MediumSeaGreen;
lbltime.ForeColor = Color.White;
if (t.Enabled)
{
MessageBox.Show("Sure !!! Your Start time is been Registered...", "Success Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
//lblstarttime.Text = DateTime.Now.ToString();
try
{
string sql = "INSERT INTO Todaywork(Username,Start_time,Date,Total_time,TodayDate)VALUES('" + lblusrname.Text + "','" + lbltime.Text + "','" + DateTime.Now.ToString() + "','" + lbltime.Text + "','"+DateTime.Now+"')";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
int x = command.ExecuteNonQuery();
conn.Close();
}
所以当我点击 form2 button.plz help 时,我想停止计时器
Form1
和之间是什么关系Form2
?如果Form2
是通过 中的按钮打开Form1
,则可以通过定义自定义属性PropertyTimer
来获取timer1
实例来实现。
表格1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
}
int i = 0;
private void timer1_Tick(object sender, EventArgs e)
{
Console.WriteLine(i++);
}
private void btOpenForm2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.PropertyTimer = timer1;
form2.Show();
}
}
表格2.cs
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Timer PropertyTimer { get; set; }
private void btStopTimer_Click(object sender, EventArgs e)
{
PropertyTimer.Stop();
}
}
如果它们之间没有关系,这里是使用Application.OpenForms 属性的通用方法。
以下是步骤:
首先,定义一个属性timer
inForm1.cs
来获取timer1 instance
.
public Timer timer
{
get { return timer1; }
set { timer1 = value; }
}
然后,通过Application.OpenForms Property
in访问计时器Form2.cs
。
private void btStopTimer_Click(object sender, EventArgs e)
{
Form1 f1 = (Form1)(Application.OpenForms["Form1"]);
f1.timer.Stop();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句