Anyway, can I break from an endless loop with a hotkey, so to speak?

I am writing this program that I want to run forever through a while loop, and whenever a user presses a certain key on the keyboard, he quits the program. I looked everywhere, but I only saw KeyEvents, but WindowsForm is not active while the program is running. Does anyone have a solution for me?

Edit: the program takes the cursor, so the activation of the event in the user interface is almost impossible

Edit two:

    public void MainMethod() 
    {
        while (true) 
        {
            if (checkBox1.Checked == true) state = State.PERFORM_ACTION_ONE;
            if (checkBox2.Checked == true) state = State.PERFORM_ACTION_TWO;
            // More stuff checking which state to assign

            switch (state) 
            {

            case State.PERFORM_ACTION_ONE:
                 DoSomething();
                 break;
            // More cases
            // I want it to be able to break anywhere in the while loop
            }
        }
    }
+4
source share
4 answers

HotKey, #, HotKey .

+2

. , :

while (keepRunning){
  // do stuff
}

, keepRunning false.

:

public partial class Form1 : Form
{
    public static bool KeepRunning;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        KeepRunning = true;
        Task.Factory.StartNew(() =>
                              {
                                  while (KeepRunning)
                                  {
                                      Trace.WriteLine("Keep running");
                                  }
                              });
    }

    private void button2_Click(object sender, EventArgs e)
    {
        KeepRunning = false;
        Trace.WriteLine("Finished Execution");
    }
}
+1

, , , " " , . BackgroundWorker.

0

Task.

WinForms will continue to work simultaneously in the user interface thread, so it can continue to receive user input. When the user asks you to stop, you can use the cancellation mechanism of task 1 to exit the cycle and the task itself.


1 See the "Cancel a task" section here .

0
source

All Articles