windows 如何在WPF桌面应用程序中修改MainWindow的默认上下文菜单

w8f9ii69  于 2023-05-08  发布在  Windows
关注(0)|答案(1)|浏览(229)

如何修改WPF桌面应用程序中MainWindow的默认上下文菜单?
下面是默认的一个:

添加菜单项是基于某些条件的,因此我需要能够在代码中而不是XAML中完成此操作。
以下是我迄今为止尝试过的:

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        if ( CanShowDevMenu )
        {
            ContextMenu menu = this.ContextMenu;

            if ( menu == null )
            {
                try
                {
                    menu = (ContextMenu)Application.Current.MainWindow.FindResource("WindowContextMenu");
                }
                catch
                {
                    menu = null;
                }
            }

            if ( menu != null )
            {
                MenuItem menuItem1 = new MenuItem() { Header = "Item 1" };
                MenuItem menuItem2 = new MenuItem() { Header = "Item 2" };
                MenuItem menuItem3 = new MenuItem() { Header = "Item 3" };

                menu.Items.Add(menuItem1);
                menu.Items.Add(menuItem2);
                menu.Items.Add(menuItem3);
            }
        }
    }

两次获取上下文菜单的尝试都不起作用--第一次返回null,第二次抛出一个异常,说找不到资源。

2vuwiymt

2vuwiymt1#

您不能修改标题栏上的默认上下文菜单,但可以将其替换为您自己的自定义菜单,例如here

private const uint WM_NCRBUTTONDOWN = 0xa4;
private const uint HTCAPTION = 0x02;

public MainWindow()
{
    InitializeComponent();
    Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    IntPtr windowhandle = new WindowInteropHelper(this).Handle;
    HwndSource hwndSource = HwndSource.FromHwnd(windowhandle);
    hwndSource.AddHook(new HwndSourceHook(WndProc));
}

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    return IntPtr.Zero;
}

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    //Message for the right click
    if ((msg == WM_NCRBUTTONDOWN) && (wParam.ToInt32() == HTCAPTION))
    {
        //Show a custom context menu
        ShowContextMenu();

        //prevent default context menu from appearing
        handled = true;
    }

    return IntPtr.Zero;
}

private void ShowContextMenu()
{
    var contextMenu = Resources["contextMenu"] as ContextMenu;
    contextMenu.IsOpen = true;
}

相关问题