繁体   English   中英

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

[英]How to stop timer of form1 when form2 button is clicked

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

Form1Form2之间的关系是什么? 如果Form2是通过Form1中的按钮打开的,则可以通过定义自定义属性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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM