无窗体通知图标应用程序
展示通知图标,启动无窗体的应用程序,未处理的异常处理
引言
关于通知图标有足够多的示例,但大多数使用包含图标的第三方组件,而 .NET 2.0 提供了通知图标。 此外,所有示例应用程序都以用户可见的窗体开始,并始终保存在内存中。当用户关闭窗体时,它们会将其隐藏。 我需要一个应用程序,仅在用户需要进行一些设置时才创建窗体,并在不将其保留在内存中的情况下关闭窗体。(由于该应用程序运行在 XPembedded 上,我们需要尽可能多地释放内存)。 此示例在 XP 和 XPembedded 上运行。它展示了如何启动一个没有窗体的应用程序,以及如何使用包含上下文菜单的通知图标来创建和显示一个窗体,让用户进行一些设置。 当用户完成操作后,窗体将从内存中删除。 它还展示了如何将一个类变成单例以及如何构建未处理的异常处理程序。
Using the Code
该代码仅作为示例。它没有任何实际用途。它确实展示了如何启动一个没有窗体的应用程序(而不是隐藏它!)。这相当简单(如果你知道如何做),只需在 program.cs 中生成的代码中更改一行代码。
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
/******************** NO Form *******************************************
/* Here you create the class that will serve as the main
* instead of loading the form and then hiding it.
* The class should call Application.Exit() when exit time comes.
* The form will only be created and kept in memory when it's actually used.
* Note that Application.Run does not start any form
* Checker is a Singleton
************************************************************************/
Checker checker = Checker.GetCheckerObject();
//Application.Run(new Form1());
Application.Run();
checker = null; //must be done to stop referencing Checker so GC can collect it.
}
使用通知图标非常简单,它不需要窗体
//notifyicon
notify = new NotifyIcon();
notify.Icon = iconstop;
notify.Text = "VriServerManager";
notify.ContextMenu = contextmenu;
//show form when double clicked
notify.DoubleClick += new EventHandler(notify_DoubleClick);
notify.Visible = true;
单例是一个在应用程序的整个生命周期中只能存在一个实例的对象。当对象在应用程序的整个生命周期中存在,并且对象所做的工作只有在一个实例中才有意义时,就会选择单例。 您可以通过将构造函数设置为 private
,在第一次引用时实例化它,并添加一个方法,使其他对象能够获取对它的引用,从而使一个类成为单例。
像这样:Private
变量到实例
private static readonly Checker checker = new Checker();
Private
构造函数
private Checker() //singleton so private constructor!
{
}
获取引用的方法
public static Checker GetCheckerObject()
{
return checker;
}
关注点
此应用程序包含用于捕获应用程序本身未捕获的异常的代码。 通常,这将导致一个未处理的异常消息框,其中包含几乎无法解释的信息。 当使用未处理的异常事件时,您可以获得您需要的信息,例如问题出处的行号。 这就是您在 main 中需要做的...
AppDomain myCurrentDomain = AppDomain.CurrentDomain;
myCurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(myCurrentDomain_UnhandledException);
处理程序...
static void myCurrentDomain_UnhandledException
(object sender, UnhandledExceptionEventArgs e)
{
//get error info here, see program.cs
}
历史
- 2007-04-21:首次绘制