C#如何在while循环中从另一个类调用void方法



所以我有两个类:ImageScannerForm1

我想做的是在while循环中继续调用ScreenCapture方法,直到满足某个条件。

此方法捕获我的屏幕,并将屏幕截图保存为PNG文件。这意味着每次我截图时,新的会替换旧的。

当我点击表单上的一个按钮时,我正在尝试这样做,所以我不知道为什么C#会给我一个错误。

但是,当ScreenCapture方法不在循环中时,我可以调用它。

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");
}
}

错误消息:

系统。运行时。InteropServices。ExternalException(0x80004005(:GDI+中发生一般错误。在系统中。绘画形象保存(字符串文件名,ImageCodecInfo编码器,EncoderParameters编码器参数(在系统中。绘画形象保存(字符串文件名,ImageFormat格式(在AutoClicker。ImageScanner。C:\Users\User1\source\repos\AutoClicker\AutoClickr\ImageScanner.cs:line 32中的ScreenCapture((在AutoClicker。单击窗体。C:\Users\User1\source\repos\AutoClicker\AutoClickr\Form1.cs:line 232中的ECFile_Click(Object sender,EventArgs e(在系统中。Windows。表格。控制OnClick(事件参数e(在系统中。Windows。表格。按钮OnClick(事件参数e(在系统中。Windows。表格。按钮OnMouseUp(鼠标事件参数(在系统中。Windows。表格。控制WmMouseUp(消息&m,鼠标按钮,Int32次点击(在系统中。Windows。表格。控制WndProc(消息&m(在系统中。Windows。表格。ButtonBase。WndProc(消息&m(在系统中。Windows。表格。按钮WndProc(消息&m(在系统中。Windows。表格。控制ControlNativeWindow。OnMessage(消息&m(在系统中。Windows。表格。控制ControlNativeWindow。WndProc(消息&m(在系统中。Windows。表格。NativeWindow。回调(IntPtr hWnd、Int32消息、IntPtr wparam、IntPtr-lparam(

这通常是由于权限限制而发生的,请为保存到的文件夹提供足够的权限

正如你所看到的,它被卡在中

系统。绘画形象保存

好的做法是从赋予每个人完全控制权开始,然后在测试和通过后尝试减少权限。

保存文件时,应提供完整路径,包括目录、文件夹、文件和文件扩展名。示例:C:abcdfilename.bmp

脱离主题,但值得一提的是:此外,考虑到您正在处理外部资源,因此输入和输出会有延迟,建议也将命令Thread.Delay(someseconds)放在保存之后,特别是如果您通过其他代码直接保存和使用保存的文件(如处理临时文件(。

在保存之前尝试将图像转换为流。请参阅下面的链接。

Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
image.Save(...);

相关内容

最新更新