I'm trying to capture a screenshot from my application and set it as the picturebox.Image
when a certain condition is true at a certain point of time. This condition has to be checked repeatedly.
For checking this condition, I am using a System.Timers.Timer
. But Clipboard.GetImage()
isn't working.
I have tried the following code, but that's not working.
timer = new System.Timers.Timer();
timer.Interval = 10000; //I'm checking the condition every 10 second or so
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
if(myCondition==true)
GetScreenshot();
}
void GetScreenshot()
{
try
{
SendKeys.SendWait("{PRTSC}");
Thread.Sleep(500);
var image = Clipboard.GetImage();
pictureBox1.Image = image;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
This doesn't work and if i try to save the image then it gives Object reference not set
kind of exception.
I've read somewhere that it happens due to the timer being MTA , so it can't get access to clipboard. I have tried using System.Windows.Forms.Timer
, but that slows the program down due to the continuous check I guess.
Is there any simple way I can get it to work without slowing down the performance. I'm quite new to C#, so a little description of how a certain solution works will be very helpful.