轉載自:https://www.cnblogs.com/celery94/archive/2010/10/26/1861371.html
1.在什麼地方找到NotifyIcon
普通的WPF控件基本上都是在該命名空間下:System.Windows.Controls,該命名空間在C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\PresentationFramework.dll下。也就是說是.net framework3.0之後才支持的。
那難道在WPF下就不能使用NotifyIcon了嗎?
在MSDN上有以下關於通知圖標的示例:http://msdn.microsoft.com/zh-cn/library/aa972170(VS.90).aspx
using System;
using System.Windows;
using System.Windows.Forms; // NotifyIcon control
using System.Drawing; // Icon
public partial class MainWindow : Window
{
NotifyIcon notifyIcon;
public MainWindow()
{
InitializeComponent();
}
void click(object sender, RoutedEventArgs e)
{
// Configure and show a notification icon in the system tray
this.notifyIcon = new NotifyIcon();
this.notifyIcon.BalloonTipText = "Hello, NotifyIcon!";
this.notifyIcon.Text = "Hello, NotifyIcon!";
this.notifyIcon.Icon = new System.Drawing.Icon("NotifyIcon.ico");
this.notifyIcon.Visible = true;
this.notifyIcon.ShowBalloonTip(1000);
}
}
其中包含NotifyIcon控件,請注意它的命名空間:System.Windows.Forms; ,該命名空間是在C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll下。所以說此處使用的NotifyIcon控件其實是.net framework 2.0就提供的在winform下面是用的控件。
2.怎麼使用NotifyIcon
App.xaml
<Application x:Class="NotifyIconStd.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ShutdownMode="OnExplicitShutdown" Startup="ApplicationStartup" Exit="ApplicationExit">
<Application.Resources>
</Application.Resources>
</Application>
App.xaml.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using Application = System.Windows.Application;
namespace NotifyIconStd
{
public partial class App : Application
{
private static NotifyIcon trayIcon;
private void ApplicationStartup(object sender, StartupEventArgs e)
{
RemoveTrayIcon();
AddTrayIcon();
}
private void AddTrayIcon()
{
if (trayIcon != null)
{
return;
}
trayIcon = new NotifyIcon
{
Icon = new System.Drawing.Icon("notifyIcon.ico"),
Text = "NotifyIconStd"
};
trayIcon.Visible = true;
ContextMenu menu = new ContextMenu();
MenuItem closeItem = new MenuItem();
closeItem.Text = "Close";
closeItem.Click += new EventHandler(delegate { this.Shutdown(); });
MenuItem addItem = new MenuItem();
addItem.Text = "Menu";
menu.MenuItems.Add(addItem);
menu.MenuItems.Add(closeItem);
trayIcon.ContextMenu = menu; //設置NotifyIcon的右鍵彈出菜單
}
private void RemoveTrayIcon()
{
if (trayIcon != null)
{
trayIcon.Visible = false;
trayIcon.Dispose();
trayIcon = null;
}
}
private void ApplicationExit(object sender, ExitEventArgs e)
{
RemoveTrayIcon();
}
}
}
該示例程序程序只是在程序啓動時,同時啓動了一個NotifyIcon,沒有其他主程序界面,可以在MenuItem的事件中添加關於彈出其他窗口的處理。