-4

I made a image recorder in a loop below, but I don't understand how I can stop recording. Here's my code

void Capture()
{
    while (true)
    {
        Bitmap bm= new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        Graphics g = Graphics.FromImage(bm);
        g.CopyFromScreen(0, 0, 0, 0, bm.Size);
        pictureBox1.Image = bm;
        Thread.Sleep(300);
    }
}

private void btnRecord_Click(object sender, EventArgs e)
{
    Thread t = new Thread(Capture);
    t.Start();
}

Please help me!

Blue
  • 22,142
  • 7
  • 54
  • 87

1 Answers1

3

Because of your loop you have a very simple ways: set a flag as a request to stop:

private volatile bool reqToStopRec = false;

void Capture()
{
    while (!reqToStopRec)
    {
        Bitmap bm= new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
        Graphics g = Graphics.FromImage(bm);
        g.CopyFromScreen(0, 0, 0, 0, bm.Size);
        pictureBox1.Image = bm;
        Thread.Sleep(300);
    }
    reqToStopRec = false;
}

private void btnRecord_Click(object sender, EventArgs e)
{
    Thread t = new Thread(Capture);
    t.Start();
}

private void btnStop_Click(object sender, EventArgs e)
{
    reqToStopRec = true;
}

In C# bool writes and reads are atomic so all you need is volatile.

bolov
  • 65,999
  • 14
  • 127
  • 202