using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WinFormNotify
{
public partial class FormNotify : Form
{
#region AnimateWindow
[DllImport("user32.dll", EntryPoint = "AnimateWindow")]
private static extern bool AnimateWindow(IntPtr handle, int ms, int flags);
#endregion
#region
private NotifyIcon notifyInfo;
#endregion
public FormNotify()
{
#region
InitializeComponent();
// 上下文菜单
ContextMenuStrip contextMenu = new ContextMenuStrip();
contextMenu.Items.Add("显示/隐藏(&V)");
contextMenu.Items.Add("系统退出(&X)");
contextMenu.ItemClicked += new ToolStripItemClickedEventHandler(contextMenu_ItemClicked);
// 系统托盘
notifyInfo = new NotifyIcon();
notifyInfo.Visible = true;
notifyInfo.Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath); // 启动程序图标。
notifyInfo.Text = AppDomain.CurrentDomain.FriendlyName; // 启动程序名称。
notifyInfo.ContextMenuStrip = contextMenu;
notifyInfo.DoubleClick += new EventHandler(notifyInfo_DoubleClick);
// 当前窗体
this.ContextMenuStrip = contextMenu;
this.StartPosition = FormStartPosition.CenterScreen;
#endregion
}
#region FormVisible
private void notifyInfo_DoubleClick(object sender, EventArgs e)
{
this.Visible = !this.Visible;
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
if (this.Visible)
{
AnimateWindow(this.Handle, 1000, 0x20010); // 居中逐渐显示。
this.Activate(); // 激活窗体并给予它焦点。
}
else
{
AnimateWindow(this.Handle, 1000, 0x10010); // 居中逐渐隐藏。
notifyInfo.ShowBalloonTip(10, notifyInfo.Text, " 在系统托盘中运行", ToolTipIcon.Info);
}
}
#endregion
#region 上下文菜单事件
private void contextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
switch (e.ClickedItem.Owner.Items.IndexOf(e.ClickedItem))
{
case 0:
this.Visible = !this.Visible;
break;
case 1:
if (MessageBox.Show(this, "您真的要退出系统吗?", "系统询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
Application.Exit();
break;
}
}
#endregion
#region FormClosing
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
this.Visible = false;
switch (e.CloseReason)
{
case CloseReason.ApplicationExitCall:
case CloseReason.TaskManagerClosing:
notifyInfo.Dispose();
break;
case CloseReason.UserClosing:
e.Cancel = true;
break;
}
}
#endregion
}
}