如何以数量递增循环保存屏幕截图?

时间:2018-08-08 05:19:11

标签: c#

我目前有一个程序在这样的循环中运行:

else if (cmd == "streams")
                {
                    Console.WriteLine("Please enter your monitors resolution");
                    Console.WriteLine("X:");
                    int xres = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Y:");
                    int yres = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Thank you, recording now started. Note that this is still in beta. Close the software to stop recording");
                    Bitmap memoryImage;
                    memoryImage = new Bitmap(xres, yres);
                    Size s = new Size(memoryImage.Width, memoryImage.Height);
                    Graphics memoryGraphics = Graphics.FromImage(memoryImage);
                    for (; ; System.Threading.Thread.Sleep(20) )
                    {
                        //Send spacebar would go here
                        p.Send(green);
                        System.Threading.Thread.Sleep(20);
                        p.Send(regular);
                        System.Threading.Thread.Sleep(20);
                        memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
                        string str = "";
                        str = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                        @"\Screenshot.png");
                        memoryImage.Save(str);

                    }

                }

每次通过循环时,屏幕截图均被保存为“屏幕截图”名称。我希望每次拍摄屏幕截图时,数字都增加1,例如,Screenshot_0001,Screenshot_0002。非常感谢。

1 个答案:

答案 0 :(得分:2)

您快到了,只需从以下位置更改for循环即可:

for (; ; System.Threading.Thread.Sleep(20) )
{
    //Send spacebar would go here
    p.Send(green);
    System.Threading.Thread.Sleep(20);
    p.Send(regular);
    System.Threading.Thread.Sleep(20);
    memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
    string str = "";
    str = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
    @"\Screenshot.png");
    memoryImage.Save(str);

}

...至:

for (var i = 0; ; i++)   // <----- note 'i'
{
    System.Threading.Thread.Sleep(20); // move sleep to here
    //Send spacebar would go here
    p.Send(green);
    System.Threading.Thread.Sleep(20);
    p.Send(regular);
    System.Threading.Thread.Sleep(20);
    memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
    string str = "";
    str = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +
                        $@"\Screenshot{i}.png");  // use 'i' here
    memoryImage.Save(str);

}

注意:我认为您可能可以简化string.Format行。读者的练习。 ;)

根据John的建议,通过将Screenshot{i}.png更改为Screenshot{i:d4}.png,您将得到更好的文件名:Screenshot0001.png,Screenshot0002.png,Screenshot0003.png,...而不是Screenshot1.png,Screenshot2.png ...