简体   繁体   English

C#停止按钮发出哔声

[英]c# stop button for beep sound

I created a simple C# app that uses the beep console. 我创建了一个使用蜂鸣控制台的简单C#应用程序。 I want to add a stop button to stop the beeping, but once the app starts to run it doesnt let me hit a close/button button. 我想添加一个停止按钮来停止蜂鸣,但是一旦应用开始运行,它不会让我按下关闭/按钮按钮。 Below is the code i have. 下面是我的代码。

private void button1_Click(object sender, EventArgs e)
{
    int int1, int2, hours;

    int1 = int.Parse(txtbox1.Text);
    int2 = int.Parse(txtbox2.Text);

    hours = ((60 / int1) * int2);
    for (int i = 0; i <= hours; i++)
    {
        Console.Beep();
        Thread.Sleep(int1 * 60000);
    }
}

The reason is that you execute button1_Click in the GUI thread. 原因是您在GUI线程中执行button1_Click When you call this method the thread will be stuck there for quite some time because you make it sleep. 当您调用此方法时,线程将在此处停留相当长的时间,因为您使其处于睡眠状态。

If you remove Thread.Sleep(int1*60000); 如果删除Thread.Sleep(int1*60000); you will notice that your application is unresponsive until it is done beeping. 您会注意到您的应用程序在完成蜂鸣之前无响应。

You should try to use a Timer instead. 您应该尝试使用Timer代替。 Something like this should work (this is based on the Windows.Forms.Timer ): 这样的事情应该可以工作(这基于Windows.Forms.Timer ):

private Timer timer = new Timer(); 

And set it up 并设置

timer.Tick += OnTick;
timer.Interval = int1 * 60000;
...


private void OnTick(object o, EventArgs e)
{
   Console.Beep();     
}

In your buttonclick you are now able to start and stop the timer: 在您的buttonclick中,您现在可以启动和停止计时器:

timer.Start();

or 要么

timer.Stop(); 

I would use a timer in this case, the reason why you can't close the form is because you are calling a sleep on the form thread from what I understand. 在这种情况下,我将使用计时器,之所以无法关闭表单,是因为您根据我的理解在表单线程上调用了sleep。 Calling a sleep on the form thread will give the impression the app has crashed. 在表单线程上调用sleep会给应用程序带来崩溃的印象。

Here is a quick sample code I built in c#, it will beep the console at the time given. 这是我用c#内置的快速示例代码,它将在指定时间发出提示音。 I hope it helps. 希望对您有所帮助。

    private void button1_Click(object sender, EventArgs e)
    {

        timer1.Tick += new EventHandler(timer_dosomething);
        timer1.Interval = 60000;
        timer1.Enabled = true;
        timer1.Start();

    }

    private void button2_Click(object sender, EventArgs e)
    {
        timer1.Stop();
    }

    void timer_dosomething(object sender, EventArgs e)
    {
        Console.Beep();
    }

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

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