0

i'M in a small project that needs to Screenshot a game. I made it Screenshot the game,and I need to make it Start and Stop the Screenshooter. But I 've a problem now...

Code:

public string path = "";
    public Form1()
    {
        InitializeComponent();
    }
    private static string _path = "C:\\temp\\not posted";
    private static int _timespan = 3000;


    private void button1_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;
        button2.Enabled = true;
        var path =@"FPSS";
        if (path != string.Empty)
            _path = path;


        _timespan = 3000;

        DirectoryInfo dir = new DirectoryInfo(_path);
        PrintScreen ps = new PrintScreen();

        if (!dir.Exists) dir.Create();

        var countScreens = 0;

        while (true)
        {
            var task=StartPrinting(ps);

            task.Wait();

            Thread.Sleep(_timespan);

            if (countScreens == 20)
            {
                System.GC.Collect();
                countScreens = 0;
            }
            countScreens++;
        }


    }
    private static async Task StartPrinting(PrintScreen ps)
    {
        var name = DateTime.Now.ToString("yyyyMMddhhmmss");
        ps.CaptureScreenToFile($"{_path}\\{name}.png", ImageFormat.Png);
        Console.WriteLine($"Printed {name}");
    }

    private void button2_Click(object sender, EventArgs e)
    {
        button1.Enabled = true;
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}

}

But in this way (with button1 start the infinite loop) I can't turn this off because the loop is running...

Any ideas? :)

Thanks!

  • 1
    Related: [breaking out of my infinite loop](https://stackoverflow.com/q/4285124/402022) - [Looping Forever in a Windows Forms Application](https://stackoverflow.com/q/8684852/402022) - [Do I need this field to be volatile?](https://stackoverflow.com/q/10307787/402022) – Theraot Feb 13 '20 at 11:58
  • You got any idea when you suppose to leave the loop? ... i mean `while (true)` keeps it running, why don't you `break` the loop when you get to `countScreens == 20`? – Veljko89 Feb 13 '20 at 11:58
  • Use a Timer instead. – Hans Passant Feb 13 '20 at 14:06
  • @HansPassant Can you give me some example? – Reborned BBIAJ Mar 11 '20 at 12:41

0 Answers0