我有一个C#应用程序表单,它在关闭和打开另一个表单之前显示一个图像3秒。守则如下:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace SampleProgram
{
public partial class failureMessage : Form
{
private Bitmap backgroundImage = null; // backgound image bitmap
private System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
private const string imagePath = @"/NandFlash/MsgRefused.png";
// Constructor
public failureMessage()
{
InitializeComponent();
this.Height = Screen.PrimaryScreen.Bounds.Height;
this.Width = Screen.PrimaryScreen.Bounds.Width;
try
{
backgroundImage = new Bitmap(imagePath);
}
catch (Exception ex)
{
throw ex;
}
myTimer.Tick += new EventHandler(TimerEventProcessor);
// Sets the timer interval to 3 seconds.
myTimer.Interval = 3000;
myTimer.Enabled = true;
}
#region Timer event
// This is the method to run when the timer is raised.
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
myTimer.Enabled = false;
myTimer.Dispose();
backgroundImage.Dispose();
backgroundImage = null;
Form1 reopenMainpage = new Form1();
reopenMainpage.Show();
this.Close();
}
#endregion
#region Paint the background
protected override void OnPaintBackground(PaintEventArgs e)
{
e.Graphics.DrawImage(backgroundImage, 0, 0);
}
#endregion
}
}然而,在随机情况下,我仍然得到以下例外情况:
System.Exception was unhandled
Message="Exception"
StackTrace:
Location: Microsoft.AGL.Common.MISC.HandleAr(PAL_ERROR ar)
Location: System.Drawing.Bitmap._InitFromMemoryStream(MemoryStream mstream)
Location: System.Drawing.Bitmap..ctor(String filename)
Location: SampleProgram.failureMessage..ctor()
Location: SampleProgram.Form1.ReceivedMsg(Object sender, FingerPrintSensorEventArgs e)
Location: SG7000.device.WndProcModification.onFGSensorTriggered(FingerPrintSensorEventArgs e)
Location: SG7000.device.WndProcModification.MyWndProc(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam)
Location: Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
Location: System.Windows.Forms.Application.Run(Form fm)
Location: SampleProgram.Program.Main()通过一些研究,我怀疑我可能没有在关闭表单之前释放位图对象或计时器对象,但是错误仍然是随机出现的。我的实现是出了什么问题,还是我忘了做什么?如有任何建议,敬请见谅。谢谢
发布于 2014-05-27 08:59:30
堆栈跟踪显示,初始化位图时会出现异常。解决办法就是不要抛出异常。
try
{
backgroundImage = new Bitmap(imagePath);
}
catch (Exception ex)
{
// Don't throw
}如果您经常加载位图,我会建议您将图片移到资源中,并从那里访问表单上的图片。
另外,将下面的行移动到Close事件处理程序。将处理程序附加到关闭事件。这将确保在窗体关闭时处理所有内容。
myTimer.Enabled = false;
myTimer.Dispose();
backgroundImage.Dispose();
backgroundImage = null;https://stackoverflow.com/questions/23884891
复制相似问题