0
從API調用我的項目時,我得到了這個異常。清除時GDI +中的一般錯誤
當我們改變某個值時,從事件調用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*/
}
}
}
爲什麼要擺脫創建圖形?我的意思是,繪製標籤不僅從onPaint中調用,而且調用錯誤的人是繪製方法。你能給我一個解釋嗎? – kfmlx 2015-02-10 06:42:13
因爲CreateGraphics()返回一個**臨時**表面,當控件刷新時會被擦除。這幾乎從來都不是正確的做法...... – 2015-02-10 08:30:14