GDI+报“参数无效”异常
在使用GDI+绘图过程中,遇到一个错误,提示"参数无效"/“Parameter not valid”,如下
-
Exception {"参数无效。"} System.Exception {System.ArgumentException} HResult -2147024809 int Source = "System.Drawing"在 System.Drawing.Graphics.GetHdc()
在 System.Drawing.BufferedGraphics.RenderInternal(HandleRef refTargetDC, BufferedGraphics buffer)
在 System.Drawing.BufferedGraphics.Render()
在 System.Windows.Forms.Control.WmPaint(Message& m)
在 System.Windows.Forms.Control.WndProc(Message& m)
在 System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

代码十分简单,就是想绘制一个矩形。本身在Paint中无法捕获到异常,
private void Panel_Main_Paint(object sender, PaintEventArgs e)
{
try
{
using (var g = e.Graphics)
{
g.DrawRectangle(Pens.Red, new Rectangle(10, 10, 100, 100));
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
异常是在 Application.ThreadException 事件中捕获到的。
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
// Handle UI thread exceptions
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
// Log the exception or show a message box
MessageBox.Show("An unhandled UI thread exception occurred:\n\n" + e.Exception.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Here you can log the exception to a file, event log, etc.
}
// Handle non-UI thread exceptions
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// Log the exception or show a message box
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("An unhandled non-UI thread exception occurred:\n\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
// Here you can log the exception to a file, event log, etc.
}
解决方法
最终发现问题所在,这个 Panel_Main 是一个自定义的用户控件,这里的的e.Graphics不能调用Dispose(即不能使用using)
修改代码如下,问题解决
private void Panel_Main_Paint(object sender, PaintEventArgs e)
{
try
{
var g = e.Graphics;
g.DrawRectangle(Pens.Red, new Rectangle(10, 10, 100, 100));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
然后,同样的Paint事件代码,如果是在Form的Paint事件中的话是正常的,一会没想明白是为什么。
1478

被折叠的 条评论
为什么被折叠?



