[WPF problems] how to disable the system menu of the WPF window (systemmenu)
Zhou yinhui
When you click the icon in the upper-left corner of the window, the displayed menu is the system menu. Sometimes you need to disable or remove some or all of the menu items. Some netizens also asked this question just now. OK, paste the Code:
To disable (remove) All menu items, call systemmenumanager. removewindowsystemmenu (window) method. If you want to disable (remove) Some menu items, call systemmenumanager. removewindowsystemmenuitem (window, int itemindex) method.
It is worth noting that if menu items are disabled, the functions associated with them will also be disabled, for example, removing "disabled" from them, the close button in the upper-right corner of the window will also be disabled. Right-click the window icon in the taskbar and no corresponding project will appear.
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)
{
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 success whandle = 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, int itemindex)
{
If (window = NULL)
{
Return;
}
Window. sourceinitialized + = delegate
{
VaR helper = new windowinterophelper (window );
Intptr success whandle = 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
};
}
}