欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > wpf工程中加入Hardcodet.NotifyIcon.Wpf生成托盘

wpf工程中加入Hardcodet.NotifyIcon.Wpf生成托盘

2025/5/2 17:07:35 来源:https://blog.csdn.net/zhang8593/article/details/139465370  浏览:    关键词:wpf工程中加入Hardcodet.NotifyIcon.Wpf生成托盘

1、在项目中用nuget引入Hardcodet.NotifyIcon.Wpf。如下图所示。

2、在App.xaml中创建托盘界面,代码是写在 App.xaml 里面

注意在application中一定要加入这一行代码: xmlns:tb="http://www.hardcodet.net/taskbar"

然后在<Application.Resources>中加入如下代码
 

    <Application.Resources><ContextMenu x:Shared="false" x:Key="SysTrayMenu"><MenuItem Height="25" Header="显示界面" Command="{Binding NotifyCommand}" CommandParameter="1"></MenuItem><MenuItem Height="25" Header="隐藏界面" Command="{Binding NotifyCommand}" CommandParameter="0"></MenuItem><Separator /><MenuItem Height="25" Header="退出服务" Command="{Binding NotifyCommand}" CommandParameter="99"></MenuItem></ContextMenu><tb:TaskbarIcon x:Key="Taskbar" ToolTipText=""DoubleClickCommand="{Binding NotifyCommand}"  DoubleClickCommandParameter="1"ContextMenu="{StaticResource SysTrayMenu}" IconSource="/jqsw.ico"><tb:TaskbarIcon.TrayToolTip><Border Background="LightYellow" CornerRadius="5" Opacity="0.8" Padding="10"><StackPanel Orientation="Vertical"><TextBlock Text="温湿度数据采集服务网口版" Foreground="Red"/><!--<TextBlock Text="{Binding SystemTime}" Foreground="Red"/>--></StackPanel></Border></tb:TaskbarIcon.TrayToolTip></tb:TaskbarIcon></Application.Resources>

3、创建ViewModelBase类。再创建TaskbarIconViewModel类继承ViewModelBase类

internal class ViewModelBase : INotifyPropertyChanged{public event PropertyChangedEventHandler  PropertyChanged ;protected void RaisePropertyChanged(string property){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));}}internal class TaskbarIconViewModel : ViewModelBase{private string systemTime;public string SystemTime{get { return systemTime; }set { systemTime = value; RaisePropertyChanged("SystemTime"); }}public DelegateCommand NotifyCommand{get{return new DelegateCommand((type) =>{if (type.ToString() == "0")Application.Current.MainWindow.Hide();if (type.ToString() == "1"){Application.Current.MainWindow.Show();Application.Current.MainWindow.Activate();}if (type.ToString() == "99")Application.Current.Shutdown();});}}} 

、在App.xaml.cs中写入如下代码:

private static System.Threading.Mutex mutex;protected override void OnStartup(StartupEventArgs e){mutex = new System.Threading.Mutex(true, "TemCollSrvTwo");if (mutex.WaitOne(0, false)){base.OnStartup(e);}else{MessageBox.Show("程序已经在运行!", "提示");this.Shutdown();} mTaskbarIcon = (TaskbarIcon)FindResource("Taskbar");mTaskbarIcon.DataContext = new TaskbarIconViewModel();}public static TaskbarIcon  mTaskbarIcon;4031

5、效果展示

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com