-1

Here's my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace _8BB_2._0
{
    public partial class Form1 : Form
    {
        public static class globalVars
        {
            public static bool spacerunning = false;
        }

        public Form1()
        {
            InitializeComponent();
            globalVars.spacerunning = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!globalVars.spacerunning)
            {
                globalVars.spacerunning = true;
                while (globalVars.spacerunning)
                {
                    Thread.Sleep(1000);
                    SendKeys.Send(" ");
                }
            }
            else if (globalVars.spacerunning)
            {
                globalVars.spacerunning = false;
            }
        }
    }
}

When I click button1 it's starts hitting space every second like it should but when I try to click it again to shut it off the application freezes and it keeps pressing space. I've tried multiple other ways but can't seem to figure out how I can do two things at once since I get locked inside of the while loop.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Prince
  • 157
  • 1
  • 2
  • 12

1 Answers1

3

Calling Thread.Sleep() will block the UI thread. Try to use async/await instead.

private async void button1_Click(object sender, EventArgs e)
{
    globalVars.spacerunning = !globalVars.spacerunning;

    while (globalVars.spacerunning)
    {
        await Task.Delay(1000);
        SendKeys.Send(" ");
    }
}

UPDATE:

You may use a Timer instead.

public class MainForm : Form
{
    private Timer timer = new Timer() { Interval = 1000 };

    public MainForm()
    {
        /* other initializations */

        timer.Enabled = false;
        timer.Tick += timer_Tick;
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        SendKeys.Send(" ");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        globalVars.spacerunning = !globalVars.spacerunning;
        timer.Enabled = globalVars.spacerunning;
    }
}
Gabor
  • 3,021
  • 1
  • 11
  • 20