首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将WPF ContextMenu与NotifyIcon结合使用

如何将WPF ContextMenu与NotifyIcon结合使用
EN

Stack Overflow用户
提问于 2022-02-15 21:17:25
回答 1查看 467关注 0票数 0

当用户单击系统托盘图标时,我想打开一个WPF ContextMenu。对于Windows,这是直截了当的,只需调用notifyIcon.ContextMenu = contextMenu就可以了.

在WPF上,我们不能轻松地设置ContextMenu,因为WPF的ContextMenu类与表单ContextMenu无关。我一直在追求的另一种选择是处理NotifyIcon的Click事件来打开WPF样式的ContextMenu。

代码语言:javascript
复制
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从来没有收到任何提示,表明用户已经离开菜单导航并应该关闭(例如,当用户单击菜单边界之外时)。任何焦点或MouseCapture事件都不会被触发,除了单击其中一项之外,我无法关闭菜单。

因此,这里的问题(稍微不同)是:如何使用WPF的ContextMenu正确地模拟NotifyIcon的ContextMenu关闭行为?

EN

回答 1

Stack Overflow用户

发布于 2022-05-23 14:50:22

我也面临着类似的问题。如果你想的话你可以试试

代码语言:javascript
复制
notifyIcon1.ContextMenuStrip = new Forms.ContextMenuStrip();
notifyIcon1.ContextMenuStrip.Items.Add("YourMenuItem",null, MenuItemEvent);

我希望这样可以解决问题。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71133508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档