程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> [WPF疑難]如何禁用WPF窗口的系統菜單(SystemMenu)

[WPF疑難]如何禁用WPF窗口的系統菜單(SystemMenu)

編輯:關於.NET

點擊窗口左上角圖標時彈出來的菜單也就是這裡所說的系統菜單(SystemMenu),有時需要禁用(移除)其中的某些或全部菜單項。剛才也有網友問到了這一點,OK,貼代碼:

要全部禁用(移除)菜單項請調用SystemMenuManager.RemoveWindowSystemMenu(Window window)方法,想部分禁用(移除)菜單項則調用SystemMenuManager.RemoveWindowSystemMenuItem(Window window, int itemIndex)方法。

值得注意的是禁用了其中的菜單項那麼與之相關聯的功能也會被禁用,比如將“關閉”從其中移除,那麼窗口的右上角的關閉按鈕也會被禁用,在任務欄的窗口圖標上右擊也不會出現相應的項目

public static class SystemMenuManager
  {
    [DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
    private static extern IntPtr GetSystemMenu(IntPtr hwnd, int revert);
    [DllImport("user32.dll", EntryPoint = "GetMenuItemCount")]
    private static extern int GetMenuItemCount(IntPtr hmenu);
    [DllImport("user32.dll", EntryPoint = "RemoveMenu")]
    private static extern int RemoveMenu(IntPtr hmenu, int npos, int wflags);
    [DllImport("user32.dll", EntryPoint = "DrawMenuBar")]
    private static extern int DrawMenuBar(IntPtr hwnd);
    private const int MF_BYPOSITION = 0x0400;
    private const int MF_DISABLED = 0x0002;
    public static void RemoveWindowSystemMenu(Window window)
    {
      if(window == null)
      {
        return;
      }
      window.SourceInitialized += window_SourceInitialized;
    }
    static void window_SourceInitialized(object sender, EventArgs e)
    {
      var window = (Window) sender;
      var helper = new WindowInteropHelper(window);
      IntPtr windowHandle = helper.Handle; //Get the handle of this window
      IntPtr hmenu = GetSystemMenu(windowHandle, 0);
      int cnt = GetMenuItemCount(hmenu);
      for (int i = cnt - 1; i >= 0; i--)
      {
        RemoveMenu(hmenu, i, MF_DISABLED | MF_BYPOSITION);
      }
    }
    public static void RemoveWindowSystemMenuItem(Window window, int itemIndex)
    {
      if (window == null)
      {
        return;
      }
      window.SourceInitialized += delegate
                      {
                        var helper = new WindowInteropHelper(window);
                        IntPtr windowHandle = helper.Handle; //Get the handle of this window
                        IntPtr hmenu = GetSystemMenu(windowHandle, 0);
                        //remove the menu item
                        RemoveMenu(hmenu, itemIndex, MF_DISABLED | MF_BYPOSITION);
                        DrawMenuBar(windowHandle); //Redraw the menu bar
                      };
  
    }
  }
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved