版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/lordwish/article/details/51788897
WPF应用要实现最小化至系统托盘运行需要使用WinForm中的方法。
using System.Windows.Forms;
namespace ServerApp
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private NotifyIcon _notifyIcon = null;
public MainWindow()
{
InitializeComponent();
InitialTray(); //最小化至托盘
}
#region 最小化系统托盘
private void InitialTray()
{
//隐藏主窗体
this.Visibility = Visibility.Hidden;
//设置托盘的各个属性
_notifyIcon = new NotifyIcon();
_notifyIcon.BalloonTipText = "服务运行中...";//托盘气泡显示内容
_notifyIcon.Text = "ServerApp";
_notifyIcon.Visible = true;//托盘按钮是否可见
_notifyIcon.Icon = new Icon(@"logo.ico");//托盘中显示的图标
_notifyIcon.ShowBalloonTip(2000);//托盘气泡显示时间
_notifyIcon.MouseDoubleClick += notifyIcon_MouseDoubleClick;
//窗体状态改变时触发
this.StateChanged += MainWindow_StateChanged;
}
#endregion
#region 窗口状态改变
private void MainWindow_StateChanged(object sender, EventArgs e)
{
if (this.WindowState == WindowState.Minimized)
{
this.Visibility = Visibility.Hidden;
}
}
#endregion
#region 托盘图标鼠标单击事件
private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
if (this.Visibility == Visibility.Visible)
{
this.Visibility = Visibility.Hidden;
}
else
{
this.Visibility = Visibility.Visible;
this.Activate();
}
}
}
#endregion
}
}