如何在单击form2按钮时停止form1的计时器



我的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按钮时停止计时器.plz帮助

Form1Form2之间的关系是什么?如果通过Form1中的按钮打开Form2,则可以通过定义自定义属性PropertyTimer来获得timer1实例。

Form1.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();
}
}

Form2.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属性的通用方法。

以下是步骤:

首先,在Form1.cs中定义一个属性timer,得到timer1 instance

public Timer timer
{
get { return timer1; }
set { timer1 = value; }
}

然后,通过Form2.cs中的Application.OpenForms Property访问计时器。

private void btStopTimer_Click(object sender, EventArgs e)
{
Form1 f1 = (Form1)(Application.OpenForms["Form1"]);
f1.timer.Stop();
}

最新更新