本文告诉大家如何在 WPF 实现在托盘显示,同时托盘可以右击打开菜单,双击执行指定的代码

NotifyIcon WPF

通过 Nuget 安装 Hardcodet.NotifyIcon.Wpf 可以快速做到在 WPF 显示托盘

因为托盘是程序的托盘,不是窗口的,所以推荐代码是写在 App.xaml.cs 里面

先创建一个托盘的界面,界面在 App.xaml 创建

托盘是需要图标的,可以从 Iconfont-阿里巴巴矢量图标库 找到好看的图标。在托盘图标需要是 16x16 32位 的 ico 文件

将图片下载放在解决方案,修改为 Resource 就可以

在 App.xaml 定义资源 TaskbarIcon 请看代码

<Application x:Class="HouneaLeabeltezairKayballjachall.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HouneaLeabeltezairKayballjachall"
xmlns:tb="http://www.hardcodet.net/taskbar"
StartupUri="MainWindow.xaml">
<Application.Resources>
<tb:TaskbarIcon x:Key="Taskbar"
IconSource="Taskbar.ico"> </tb:TaskbarIcon>
</Application.Resources>
</Application>

上面代码需要替换 Class="HouneaLeabeltezairKayballjachall.App" 为自己的项目

打开 App.xaml.cs 获取资源,资源只有在获取的时候才会创建,创建了 TaskbarIcon 就会在托盘显示

        protected override void OnStartup(StartupEventArgs e)
{
_taskbar = (TaskbarIcon) FindResource("Taskbar");
base.OnStartup(e);
} private TaskbarIcon _taskbar;

运行代码可以看到图片显示图标,下面的图片是我的图标

鼠标移动在托盘上面显示文字,可以在 TaskbarIcon 添加代码

        <tb:TaskbarIcon x:Key="Taskbar"
ToolTipText="鼠标移动上显示的文字"
IconSource="Taskbar.ico"> </tb:TaskbarIcon>

双击托盘运行代码需要添加命令,创建一个 ViewModel 用来绑定命令

    public class DelegateCommand : ICommand
{
public Action CommandAction { get; set; }
public Func<bool> CanExecuteFunc { get; set; } public void Execute(object parameter)
{
CommandAction();
} public bool CanExecute(object parameter)
{
return CanExecuteFunc == null || CanExecuteFunc();
} public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}

添加一些功能,显示窗口,隐藏窗口

    public class NotifyIconViewModel
{
/// <summary>
/// 如果窗口没显示,就显示窗口
/// </summary>
public ICommand ShowWindowCommand
{
get
{
return new DelegateCommand
{
CanExecuteFunc = () => Application.Current.MainWindow == null,
CommandAction = () =>
{
Application.Current.MainWindow = new MainWindow();
Application.Current.MainWindow.Show();
}
};
}
} /// <summary>
/// 隐藏窗口
/// </summary>
public ICommand HideWindowCommand
{
get
{
return new DelegateCommand
{
CommandAction = () => Application.Current.MainWindow.Close(),
CanExecuteFunc = () => Application.Current.MainWindow != null
};
}
} /// <summary>
/// 关闭软件
/// </summary>
public ICommand ExitApplicationCommand
{
get
{
return new DelegateCommand { CommandAction = () => Application.Current.Shutdown() };
}
}
}

在界面绑定代码

        <tb:TaskbarIcon x:Key="Taskbar"
ToolTipText="鼠标移动上显示的文字"
DoubleClickCommand="{Binding ShowWindowCommand}"
IconSource="Taskbar.ico"> </tb:TaskbarIcon>

这时的 TaskbarIcon 还没有 ViewModel 可以通过下面的方式

        <tb:TaskbarIcon x:Key="Taskbar"
ToolTipText="鼠标移动上显示的文字"
DoubleClickCommand="{Binding ShowWindowCommand}"
IconSource="Taskbar.ico">
<tb:TaskbarIcon.DataContext>
<local:NotifyIconViewModel />
</tb:TaskbarIcon.DataContext>
</tb:TaskbarIcon>

现在双击就可以打开 MainWindow 因为默认 MainWindow 是打开的,比较难看到双击打开。在 App.xaml 去掉默认打开 MainWindow 需要找到下面的代码

StartupUri="MainWindow.xaml"

现在尝试不让默认打开 MainWindow 运行软件,可以看到托盘显示图标,双击图标才可以打开界面

如果要右击显示菜单,需要在 App.xaml 添加定义

        <ContextMenu x:Shared="false" x:Key="SysTrayMenu">
<MenuItem Header="显示窗口" Command="{Binding ShowWindowCommand}" />
<MenuItem Header="关闭窗口" Command="{Binding HideWindowCommand}" />
<Separator />
<MenuItem Header="退出" Command="{Binding ExitApplicationCommand}" />
</ContextMenu>

在 TaskbarIcon 使用菜单

        <tb:TaskbarIcon x:Key="Taskbar"
ContextMenu="{StaticResource SysTrayMenu}"
ToolTipText="鼠标移动上显示的文字"
DoubleClickCommand="{Binding ShowWindowCommand}"
IconSource="Taskbar.ico">
<tb:TaskbarIcon.DataContext>
<local:NotifyIconViewModel />
</tb:TaskbarIcon.DataContext>
</tb:TaskbarIcon>

因为在 ViewModel 已经写好代码,所以现在就可以运行

默认的软件设置是关闭最后一个窗口的时候应用就关闭,通过设置 App.ShutdownMode 可以在调用退出才关闭,打开 App.xaml 添加代码

 ShutdownMode="OnExplicitShutdown"

本文的代码

WPF 托盘显示 右击打开菜单,双击打开软件-CSDN下载

下面还有一些高级的使用

定义托盘鼠标移动上去的文字颜色

            <tb:TaskbarIcon.TrayToolTip>
里面可以添加控件
</tb:TaskbarIcon.TrayToolTip>
        <tb:TaskbarIcon x:Key="Taskbar"
ContextMenu="{StaticResource SysTrayMenu}"
DoubleClickCommand="{Binding ShowWindowCommand}"
IconSource="Taskbar.ico">
<tb:TaskbarIcon.TrayToolTip>
<Border
Background="White"
BorderBrush="Orange"
BorderThickness="2"
CornerRadius="4"
Opacity="0.8"
Width="160"
Height="40">
<TextBlock
Text="hello world"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
</tb:TaskbarIcon.TrayToolTip>
<tb:TaskbarIcon.DataContext>
<local:NotifyIconViewModel />
</tb:TaskbarIcon.DataContext>
</tb:TaskbarIcon>

因为可以添加控件,发挥你的想法,如添加按钮

        <tb:TaskbarIcon x:Key="Taskbar"
ContextMenu="{StaticResource SysTrayMenu}"
DoubleClickCommand="{Binding ShowWindowCommand}"
IconSource="Taskbar.ico">
<tb:TaskbarIcon.TrayToolTip>
<Border
Background="White"
BorderBrush="Orange"
BorderThickness="2"
CornerRadius="4"
Opacity="0.8"
Width="160">
<Grid>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="可以放文字"></TextBlock>
<Button Margin="10,100,10,10" Content="可以放按钮"></Button>
</Grid>
</Border>
</tb:TaskbarIcon.TrayToolTip>
<tb:TaskbarIcon.DataContext>
<local:NotifyIconViewModel />
</tb:TaskbarIcon.DataContext>
</tb:TaskbarIcon>

显示气泡

通过下面的代码可以显示气泡

Taskbar.ShowBalloonTip("标题", "内容", BalloonIcon.Info);

如果需要自定义气泡,定义一个继承 UIElement 的类,然后传入 TaskbarIcon.ShowCustomBalloon 就可以

如已经定义了 FancyBalloon 气泡,可以通过下面的代码

 FancyBalloon balloon = new FancyBalloon();
TaskbarIcon.ShowCustomBalloon(balloon, PopupAnimation.Slide, 4000 /*多少时间就隐藏*/);

代码:NotifyIcon WPF — Bitbucket

我搭建了自己的博客 https://blog.lindexi.com/ 欢迎大家访问,里面有很多新的博客。只有在我看到博客写成熟之后才会放在csdn或博客园,但是一旦发布了就不再更新

如果在博客看到有任何不懂的,欢迎交流,我搭建了 dotnet 职业技术学院 欢迎大家加入


本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接:http://blog.csdn.net/lindexi_gd ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系

WPF 托盘显示的更多相关文章

  1. WPF 图片显示中的保留字符问题

    在WPF中显示一张图片,本是一件再简单不过的事情.一张图片,一行XAML代码即可. 但是前段时间遇到了一件奇怪的事: 开发机上运行正常的程序,在某些客户机器上却显示不了图片,而且除了这个问题,其它运行 ...

  2. C# winForm程序开机启动和托盘显示 (转http://blog.csdn.net/xinyue3054/article/details/6599508)

    这段时间一直进行cs项目,故整理下开机自动运行.托盘.显示.隐藏. (1).在窗口上点击关闭按钮或者最小化时将托盘显示: (2).双击托盘图标显示窗口: (3).右键点击托盘图标提供三个菜单选项,“退 ...

  3. C# 开机自启动和最小化托盘显示

    C# 开机自启动和最小化托盘显示 一.      C# 开机自启动 C# 开机自启动,这个功能是大多数服务型软件很常用一个功能,但是这个功能确是不 太好做,花了两天想对策.不过最终呢,结果还是很满意的 ...

  4. Winform设置托盘程序,托盘显示

    1.拖一个NotifyIcon,一个ContextMenuStrip控件到主窗体中 2.设置notifyIcon1,一个contextMenuStrip1(如下图) Icon为托盘图标,Text托盘显 ...

  5. 在WPF中显示动态GIF

    在我们寻求帮助的时候,最不愿意听到的答复是:很抱歉,在当前版本的产品中还没有实现该功能... 在WPF中显示动态的GIF图像时便遇到了这样的问题,WPF中强大的Image控件却不支持动态的GIF(其只 ...

  6. WPF 循环显示列表

    原文:WPF 循环显示列表 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/SANYUNI/article/details/79423707 项目需要 ...

  7. WPF 窗体显示最前端

    原文:WPF 窗体显示最前端 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/jjx0224/article/details/8782845 如何做一 ...

  8. WPF 远程显示原图 当前主页面 工具栏 一个Window页面的元素适用一个效果

    http://www.jb51.net/article/98384.htm 1.wpf远程显示原图: Stretch="Fill" + ; 主要是因为那个950和650,据显示位置 ...

  9. WPF:行列显示

    新建显示病人信息控件PatientElement Add-->NewItem-->WPF-->UserControl(WPF),名称:PatientElement.xmal < ...

随机推荐

  1. CMake学习笔记五-依赖库添加

    # # 项目名称 # SET(WIS_PROJECT_NAME EXAMPLE) # dependencies SET(DEPENDENCIES #依赖第三方库 ) #Qt模块 SET(QT_MODU ...

  2. Sublime Text3 安装less

    1.安装Sublime 插件 (1)安装LESS插件:因为Sublime不支持Less语法高亮,所以,先安装这个插件,方法: ctrl+shift+p>install Package>输入 ...

  3. Java练习 SDUT-2192_救基友记2

    救基友记2 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 屌丝WP的好基友CZ又被妖鬼给抓走了(CZ啊,CZ-.怎么说 ...

  4. Kernal Panic - Not syncing : VFS: unable to mount root fs on unknown-block

    升级了一下centos6.5 执行了 yum -y update reboot 出现了以下问题: Kernal Panic - Not syncing : VFS: unable to mount r ...

  5. LeetCode97 Interleaving String

    Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. (Hard) For example,Giv ...

  6. 基于PyTorch的Seq2Seq翻译模型详细注释介绍(一)

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/qysh123/article/detai ...

  7. 在 Linux 启动或重启时执行命令与脚本

    有时可能会需要在重启时或者每次系统启动时运行某些命令或者脚本.我们要怎样做呢?本文中我们就对此进行讨论. 我们会用两种方法来描述如何在 CentOS/RHEL 以及 Ubuntu 系统上做到重启或者系 ...

  8. 2019-10-23-WPF-使用-SharpDx-渲染博客导航

    title author date CreateTime categories WPF 使用 SharpDx 渲染博客导航 lindexi 2019-10-23 21:10:13 +0800 2019 ...

  9. 公司安装mariaDB-5.5.52和Jdk 7

    转自:http://www.cnblogs.com/kgdxpr/p/3209009.html vi /etc/yum.repos.d/MariaDB.repo 加入下面内容 [mariabd]nam ...

  10. react 问题记录

    1.控制台报错: Uncaught Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be add ...