我真的很想在winforms中使用C#中的事件处理程序,目前我有以下错误:
错误1“DotFlickScreenCapture.ScreenCapture”类型不能用作泛型类型或方法“System.EventHandler”中的类型参数“TEventArgs”。没有从'DotFlickScreenCapture.ScreenCapture'到'System.EventArgs'的隐式引用转换。
我试图找到一种方法来击败这个错误,但到目前为止,我的谷歌搜索没有发现任何东西。
此错误指向的行是这一行:
public EventHandler<ScreenCapture> capture;
据我所知,这堂课:
public class ScreenCapture
{
public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
public event StatusUpdateHandler OnUpdateStatus;
public bool saveToClipboard = true;
public void CaptureImage(bool showCursor, Size curSize, Point curPos, Point SourcePoint, Point DestinationPoint, Rectangle SelectionRectangle, string FilePath, string extension)
{
Bitmap bitmap = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(SourcePoint, DestinationPoint, SelectionRectangle.Size);
if (showCursor)
{
Rectangle cursorBounds = new Rectangle(curPos, curSize);
Cursors.Default.Draw(g, cursorBounds);
}
}
if (saveToClipboard)
{
Image img = (Image)bitmap;
Clipboard.SetImage(img);
if (OnUpdateStatus == null) return;
ProgressEventArgs args = new ProgressEventArgs(img);
OnUpdateStatus(this, args);
}
else
{
switch (extension)
{
case ".bmp":
bitmap.Save(FilePath, ImageFormat.Bmp);
break;
case ".jpg":
bitmap.Save(FilePath, ImageFormat.Jpeg);
break;
case ".gif":
bitmap.Save(FilePath, ImageFormat.Gif);
break;
case ".tiff":
bitmap.Save(FilePath, ImageFormat.Tiff);
break;
case ".png":
bitmap.Save(FilePath, ImageFormat.Png);
break;
default:
bitmap.Save(FilePath, ImageFormat.Jpeg);
break;
}
}
}
}
public class ProgressEventArgs : EventArgs
{
public Image CapturedImage { get; private set; }
public ProgressEventArgs(Image img)
{
CapturedImage = img;
}
}
之前有没有人遇到过此错误?是这样,我怎么能克服它?
答案 0 :(得分:6)
ScreenCapture
类必须从EventArgs
类派生,以便按您希望的方式使用。
public class ScreenCapture : EventArgs
然后(为了避免误解),它应该被命名为ScreenCaptureEventArgs
。考虑到这一点,创建一个派生自ScreenCaptureEventArgs
并包含属性EventArgs
的类ScreenCapture
会更容易,该属性是您已经拥有的类的实例。
就像那样:
public class ScreenCaptureEventArgs : EventArgs
{
public ScreenCaptureEventArgs(ScreenCapture c)
{
Capture = c;
}
public ScreenCapture Capture { get; private set; }
}
public event EventHandler<ScreenCaptureEventArgs> ScreenCaptured;