如何将按钮单击事件设为切换按钮?

时间:2014-08-07 11:33:22

标签: c# winforms

private void demoAlertToolStripMenuItem_Click(object sender, EventArgs e)
{
     demoAlertToolStripMenuItem.ForeColor = Color.Red;
     timer1.Stop();
}

在第一次点击它会将颜色更改为红色并将停止计时器1现在我想要如果我再次点击按钮它会将颜色改回原来的颜色黑色并继续timer1。

4 个答案:

答案 0 :(得分:1)

您可以查看Timer.Enabled属性并进行更改,例如:

private void demoAlertToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (timer1.Enabled) // timer is running
    {
        demoAlertToolStripMenuItem.ForeColor = Color.Red;
        timer1.Stop();
    }
    else  // timer is stopped
    {
        demoAlertToolStripMenuItem.ForeColor = Color.Black;
        timer1.Start();
    }     
}

答案 1 :(得分:1)

当您致电"Start"时,它会将{已设置为TRUE"Stop"将其设置为FALSE

这是你想要的吗?

private void demoAlertToolStripMenuItem_Click(object sender, EventArgs e)
{
    if(timer1.Enabled)
    {
        demoAlertToolStripMenuItem.ForeColor = Color.Red;
        timer1.Stop();
    }
    else
    {
        demoAlertToolStripMenuItem.ForeColor = Color.Black;
        timer1.Start();
    }
}

答案 2 :(得分:1)

或者更短的一个:

private void demoAlertToolStripMenuItem_Click(object sender, EventArgs e)
{
    timer1.Enabled = !timer1.Enabled;
    demoAlertToolStripMenuItem.ForeColor = timer1.Enabled ? Color.Black : Color.Red;
}

答案 3 :(得分:1)

考虑将工具条按钮配置为“切换”按钮,即在单击时保持按下状态,直到再次单击该按钮为止。这样,用户将看到您的动作/计时器当前是否已启用的直观线索:

demoAlertToolStripMenuItem.CheckOnClick = true; // this makes the button a "toggle" one

void demoAlertToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
    if (demoAlertToolStripMenuItem.Checked)
    {
        // do one action, e.g. start the timer
        …
    }
    else
    {
        // undo the action, e.g. stop the timer
        …
    }
}