我有一个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()
经过一些研究,我怀疑可能是在关闭表单之前我没有处理位图对象或计时器对象,但错误仍然是随机时间。我的实施有问题,或者我忘了做某事?任何建议表示赞赏。感谢
答案 0 :(得分:0)
堆栈跟踪显示初始化位图时发生异常。解决方法是不抛出异常。
try
{
backgroundImage = new Bitmap(imagePath);
}
catch (Exception ex)
{
// Don't throw
}
如果经常加载位图,我建议将图片移动到资源并从那里访问表单。
此外,将下面的行移动到Close事件处理程序。将处理程序附加到Close事件。这将确保在表单关闭时处理所有内容。
myTimer.Enabled = false;
myTimer.Dispose();
backgroundImage.Dispose();
backgroundImage = null;