Date: 2008jul3
Update: 2025oct23
Platform: win32
Language: C/C++
Keywords: enable, disable, grey, gray, programmatically
Q. Win32: How to disable a Window's close button?
The [X] thing in the top-right corner.
A. Here's a little function that does the trick:
// Disable or enable the [X] button in top-right corner
BOOL EnableCloseButton(const HWND hwnd, const BOOL bState) {
HMENU hMenu;
if (hwnd == NULL) return FALSE;
if ((hMenu = GetSystemMenu(hwnd, FALSE)) == NULL) return FALSE;
const UINT uExtra = bState ? MF_ENABLED : (MF_DISABLED | MF_GRAYED);
return EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | uExtra) != -1;
}
// The MFC version...
#ifdef _MFC_VER
// Disable or enable the [X] button in top-right corner
BOOL EnableCloseButton(const CWnd *wnd, const BOOL bState) {
CMenu *menu;
if (wnd == NULL) return FALSE;
if ((menu = wnd->GetSystemMenu(FALSE)) == NULL) return FALSE;
const UINT uExtra = bState ? MF_ENABLED : MF_GRAYED;
return menu->EnableMenuItem(SC_CLOSE, MF_BYCOMMAND | uExtra) != -1;
}
#endif
void ExampleUse() {
// To disable:
EnableCloseButton(hwnd, FALSE);
// To disable in MFC:
EnableCloseButton(AfxGetMainWnd(), FALSE);
}