So I have 2 classes: ImageScanner
and Form1
What I want to do is keep calling the ScreenCapture
method in my while loop until a certain condition is met.
This Method captures my screen and saves the screenshot as a PNG
file in the same place. This means every time I take a screenshot, the new one replaces the old one.
I am trying to do this when I click a button on my form so I don't know why C# is giving me an error.
I can however call the ScreenCapture
method when it is not in my loop.
class ImageScanner
{
public static void ScreenCapture()
{
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppPArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
// Save the screenshot to the specified path that the user has chosen.
bmpScreenshot.Save("Screenshot.png", ImageFormat.Png);
}
}
public partial class ClickForm : Form
{
private void ECFile_Click(object sender, EventArgs e)
{
int j = 0;
while (j < 20)
{
j += 1;
ImageScanner.ScreenCapture();
}
MessageBox.Show("found");
}
}
Error Message:
System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+. at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) at System.Drawing.Image.Save(String filename, ImageFormat format) at AutoClicker.ImageScanner.ScreenCapture() in C:\Users\User1\source\repos\AutoClicker\AutoClicker\ImageScanner.cs:line 32 at AutoClicker.ClickForm.ECFile_Click(Object sender, EventArgs e) in C:\Users\User1\source\repos\AutoClicker\AutoClicker\Form1.cs:line 232 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)