Search code examples
c#winformsloopskeypressbreak

Press key to break a loop


C# windows form has problem that when a loop is executed, it disables all other events. So when a loop is too long, I can't stop the program properly (can't press the close button). Anyone know how to solve this problem, please help. To simplify the problem, here is a sample code.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.S)
        {
            CheckLoop();
        }
    }

    void CheckLoop()
    {
        progressBar1.Maximum = 9999999;
        progressBar1.Value = 0;
        while (progressBar1.Value != progressBar1.Maximum)
        {
            progressBar1.Value++;
            if (Control.ModifierKeys == Keys.Alt)//Did not break when press Alt???
                break;
        }
    }
}

The question is how to make the Alt key works the way it supposes to work? Thanks for reading.


Solution

  • Try this my friend:

        void CheckLoop()
        {
            progressBar1.Maximum = 9999999;
            progressBar1.Value = 0;
            while (progressBar1.Value != progressBar1.Maximum)
            {
                progressBar1.Value++;
                Application.DoEvents();
                if (Control.ModifierKeys == Keys.Alt)//it should stop now
                    break;
            }
        }
    

    Application.DoEvents() works if you want a quick solution.

    Edit:

    Depending on what you're doing you might have different needs. I consider the timer to be really easy to use as well.

    Let's see your code using a timer:

    Prerequisites :

    1-Add a timer component from the toolbox
    2-Double click the added timer to quickly access its Tick event handler.

    private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.S)
            {
                progressBar1.Maximum = 100;
                progressBar1.Value = 0;
                UpdateProgress.Enabled = true;
            }
        }
    
        private void UpdateProgress_Tick(object sender, EventArgs e)
        {
            //Do some work
            if (progressBar1.Value < progressBar1.Maximum) 
            {
                progressBar1.Value++;
            }
    
    
            if (Control.ModifierKeys == Keys.Alt)
            {
                UpdateProgress.Enabled = false;
            }
        }