我如何使按钮单击事件切换按钮

本文关键字:按钮 事件 单击 何使 | 更新日期: 2023-09-27 18:16:51

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

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

我如何使按钮单击事件切换按钮

您可以检查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();
    }     
}

当您调用"Start"时,它将Enabled设置为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();
    }
}

或者短一点:

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

考虑将工具条按钮配置为"切换"按钮,即当单击时保持按下状态,直到再次单击为止。这样用户就可以看到你的动作/计时器当前是否启用:

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
        …
    }
}