[英]How to use a WPF ContextMenu with NotifyIcon
當用戶單擊系統托盤圖標時,我想打開一個 WPF ContextMenu。 對於 Windows 窗體,這很簡單,只需調用notifyIcon.ContextMenu = contextMenu
。
在 WPF 上,我們不能輕易設置 ContextMenu,因為 WPF 的 ContextMenu 類與 Forms ContextMenu 無關。 我一直在追求的替代方法是處理 NotifyIcon 的 Click 事件以打開 WPF 樣式的 ContextMenu。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// This is intended to be a system tray application so we hide the window
this.Visibility = Visibility.Hidden;
// Winform context menu
// The context menu closes when the user clicks anywhere outside the menu
// The user can navigate the menu with the keyboard arrows and close with ESC
var notifyIcon1 = new System.Windows.Forms.NotifyIcon();
var contextMenu = new System.Windows.Forms.ContextMenu();
var menuItem = new System.Windows.Forms.MenuItem();
menuItem.Text = "WinForm Menu Item";
contextMenu.MenuItems.Add(menuItem);
notifyIcon1.ContextMenu = contextMenu;
notifyIcon1.Icon = Properties.Resources.ico;
notifyIcon1.Visible = true;
// WPF context menu
// The user cannot close the menu by clicking outside its bounds
// Does not detect any keyboard input
var notifyIcon2 = new System.Windows.Forms.NotifyIcon();
notifyIcon2.Icon = Properties.Resources.ico;
notifyIcon2.Visible = true;
notifyIcon2.Click += NotifyIcon2_Click;
}
private void NotifyIcon2_Click(object sender, EventArgs e)
{
var contextMenu = new ContextMenu();
var menuItem = new MenuItem();
menuItem.Header = "WPF Menu Item";
contextMenu.Items.Add(menuItem);
contextMenu.IsOpen = true;
}
}
這種方法的問題是 WPF ContextMenu 永遠不會得到任何提示用戶已經離開菜單並應該關閉(例如,當用戶在菜單邊界之外單擊時)。 沒有觸發任何 Focus 或 MouseCapture 事件,除了單擊其中一項之外,我無法關閉菜單。
所以這里的問題,稍微不同的是:如何使用 WPF 的 ContextMenu 正確模擬 NotifyIcon 的 ContextMenu 關閉行為?
我遇到了類似的問題。 如果你願意,你可以試試
notifyIcon1.ContextMenuStrip = new Forms.ContextMenuStrip();
notifyIcon1.ContextMenuStrip.Items.Add("YourMenuItem",null, MenuItemEvent);
我希望這能解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.