Search code examples
c#datetimescreenshottimespanstopwatch

Taking Screenshot after 1 minute


I have two questions:

1. How can I take screenshot after every 1 min, when a key is pressed E.g.

  1. 10:00: -> key pressed -> Img1
  2. 10:01: -> key pressed -> Img2
  3. 10:02: -> key pressed -> Img3

2. How can I iterate the image chain assuming my program runs for 5-10 mins

  string ImgPath = @"D:\"Img" + iteration + ".bmp";
  Bitmap btmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
  Graphics g = Graphics.FromImage(btmp);
  g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, btmp.Size, CopyPixelOperation.SourceCopy);

if (any key is pressed)
if (time difference is 1 min)
btmp.Save(ImgPath, System.Drawing.Imaging.ImageFormat.Bmp);

Also if there is a more better way to take screenshot please share here.

Thanks!


Solution

  • What you want to do is start (or restart) a Stopwatch when you take a picture. Then, whenever a key is pressed, you check if the Stopwatch has been running for at least a minute. If it has, you take the picture and reset the stopwatch. The general idea:

    // Start the clock when the program starts.
    private Stopwatch _pictureTimer = Stopwatch.StartNew();
    
    // Wait this long between pictures
    private readonly TimeSpan _pictureWaitTime = TimeSpan.FromMinutes(1.0);
    
    // Come here when key is pressed.
    if (_pictureTimer.Elapsed > _pictureWaitTime)
    {
        // take the screen shot
        // and then reset the stopwatch
        _pictureTimer.Restart();
    }
    

    If you want to number the pictures, keep a variable that you update every time. When the program starts, you initialize it:

    private int _pictureNumber = 1;
    

    And whenever you take a picture, you increment it. That is, after resetting the stopwatch, just do:

    _pictureNumber = pictureNumber + 1;