从API调用我的项目时出现了这个异常。
当我们更改某个值时从事件调用throw消息的方法,它将重新绘制背景并重绘字符串。当正常使用应用程序时,这种情况永远不会发生,但是当我从API更改了值时,有时会抛出它。
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
at System.Drawing.Graphics.Clear(Color color) at MyCompany.Project.GUI.Drawable.DrawLabel() in D:\Source\MyCompany\Project\GUI\Drawable.cs:line 191
at MyCompany.Project.GUI.Drawable.OnPaint(PaintEventArgs e) in D:\Source\MyCompany\Project\GUI\Drawable.cs:line 26
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
at System.Windows.Forms.Control.WmPaint(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.UserControl.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)
以下是我的代码的样子
public class Drawable : UserControl
{
private Graphics g;
public void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawLabel();
}
private void DrawLabel()
{
if ((TopLabels != null) || (LeftLabels != null))
{
g.Clear( BackColor ); //tje error is in here.
g = CreateGraphics();
/* another things to do*/
}
}
}
答案 0 :(得分:2)
您需要将图形从OnPaint()传递给DrawLabel()方法。
变化:
DrawLabel();
要:
DrawLabel(e.Graphics);
并改变:
private void DrawLabel()
要:
private void DrawLabel(Graphics g)
...并摆脱CreateGraphics()调用。