WPFNotifyIcon采取
原创private NotifyIcon _notifyIcon;//托盘控件
private ContextMenuStrip _nfmenuStrip;//右键快捷菜单
//初始化托盘
private void InitialTray()
{
_nfmenuStrip = new ContextMenuStrip();
_nfmenuStrip.Items.Add("退出", null, Exit_Click);
_notifyIcon = new NotifyIcon();
_notifyIcon.ContextMenuStrip = _nfmenuStrip;//关键快捷菜单
_notifyIcon.Visible = true;//托盘图标可见
_notifyIcon.Text = "";//名称
_notifyIcon.BalloonTipTitle = "";
_notifyIcon.BalloonTipText = "";
_notifyIcon.BalloonTipIcon = ToolTipIcon.Info;
_notifyIcon.MouseDoubleClick += notifyIcon_MouseDoubleClick;
//正常使用程序路径直接_notifyIcon.Icon = new Icon(ico图片路径)即可,因公司有文件加密操作,所以这样写无法使用图片,所以要用文件流再转成ico
_notifyIcon.Icon = GetIconByResource("Test.Images.Logo.ico");//参数注释:我的项目名是Test,项目下有个Images文件夹,Images里有个Logo.ico(切记要把图片右键属性-》生成操作Resource改为"嵌入的资源")
}
//根据程序集中加载资源
private Icon GetIconByResource(string name)
{
var assembly = Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream(name);
Icon ico = new Icon(stream);
return ico;
}
//托盘图标双击事件
private void notifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button == MouseButtons.Left)
{
if(this.Visibility != Visibility.Hidden)
{
this.WindowState = WindowState.Normal;
this.Visibility = Visibility.Visible;
this.Activate();
}else
{
this.Visibility = Visibility.Visible;
this.Activate();
}
}
}
//快捷菜单-》退出按钮事件
private void Exit_Click(object sender, EventArgs e)
{
_notifyIcon.Visible = false;//托盘图片不可见
Application.Current.Shutdown();//退出程序
}
//窗体关闭按钮事件
private void CloseBtn_Click(object sender, RoutedEventArgs e)
{
this.Hide();
this.Visibility = Visibility.Hidden;
_notifyIcon.ShowBalloonTip(1);
}
//窗体最小化按钮事件
private void MinBtn_Click(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
this.Visibility = Visibility.Visible;
}
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除