I needed an option that would disable the close conditionally (like the standard MessageBox
does for a YesNo
question) so the accepted answer wouldn't work for me or possibly I failed to see how I could get it to work. I ended up with this
Private Const MF_BYPOSITION As Int32 = &H400
Private Const MF_REMOVE As Int32 = &H1000
Private Declare Auto Function GetSystemMenu Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal bRevert As Int32) As IntPtr
Private Declare Auto Function GetMenuItemCount Lib "user32.dll" (ByVal hMenu As IntPtr) As Int32
Private Declare Function DrawMenuBar Lib "user32.dll" (ByVal hwnd As IntPtr) As Boolean
Private Declare Auto Function RemoveMenu Lib "user32.dll" (ByVal hMenu As IntPtr, ByVal nPosition As Int32, ByVal wFlags As Int32) As Int32
Public Sub DisableCloseButton(ByVal hwnd As IntPtr)
Dim hMenu As IntPtr, n As Int32
hMenu = GetSystemMenu(hwnd, 0)
If Not hMenu.Equals(IntPtr.Zero) Then
n = GetMenuItemCount(hMenu)
If n > 0 Then
RemoveMenu(hMenu, n - 1, MF_BYPOSITION Or MF_REMOVE)
RemoveMenu(hMenu, n - 2, MF_BYPOSITION Or MF_REMOVE)
DrawMenuBar(hwnd)
End If
End If
End Sub
Call it via
DisableCloseButton(MyForm.Handle)
As I was using it for a custom message box, I didn't test how to re-enable.