' 利用 Windows API
' 下面的内容在模块中定义
Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Declare Function GetSystemMenu Lib "user32" (ByVal hWnd As Long, ByVal bRevert As Long) As Long
Declare Function EnableMenuItem Lib "user32" (ByVal hMenu As Long, ByVal wIDEnableItem As Long, ByVal wEnable As Long) As Long
Public Const SC_CLOSE As Long = 61536
Public Const MF_BYCOMMAND As Long = &H0
Public Const MF_GRAYED As Long = &H1
Public Const MF_ENABLED As Long = &H0
' 下面是窗体中的内容
Dim hWnd As Long
Dim bState As Long
' 窗体中有个按钮 Command_Button1, 它可以切换 SC_CLOSE 的状态
Private Sub CommandButton1_Click()
Dim i As Long
Dim hMenu As Long
If hWnd = 0 Then hWnd = FindWindow(vbNullString, Me.Caption)
If hWnd <> 0 Then
hMenu = GetSystemMenu(hWnd, False)
If bState = MF_GRAYED Then
bState = MF_ENABLED
Else
bState = MF_GRAYED
End If
i = EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND Or bState)
End If
End Sub
' 窗体初始化时将 SC_CLOSE 禁止掉
Private Sub UserForm_Initialize()
Dim hMenu As Long
If hWnd <> 0 Then Exit Sub
hWnd = FindWindow(vbNullString, Me.Caption)
If hWnd <> 0 Then
hMenu = GetSystemMenu(hWnd, False)
EnableMenuItem hMenu, SC_CLOSE, MF_BYCOMMAND Or MF_GRAYED
bState = MF_GRAYED
End If