在Windows窗体中禁用关闭按钮

时间:2010-06-19 11:07:16

标签: winforms

我在互联网上找到了这个代码但不确定如何使用它。我还需要在工作完成后重新启用它。请帮助。

Private Const CP_NOCLOSE_BUTTON As Integer = &H200

Protected Overloads Overrides ReadOnly Property CreateParams() As CreateParams
    Get
        Dim myCp As CreateParams = MyBase.CreateParams
        myCp.ClassStyle = myCp.ClassStyle Or CP_NOCLOSE_BUTTON
        Return myCp
    End Get
End Property

1 个答案:

答案 0 :(得分:3)

您可以将其粘贴到表单的代码中以使用它。然而,这会永久禁用关闭按钮。动态地执行它需要非常不同的代码,您必须修改系统菜单。将此代码粘贴到表单中,并使用逻辑中的CloseEnabled属性:

Public Property CloseEnabled() As Boolean
    Get
        Return mCloseEnabled
    End Get
    Set(ByVal value As Boolean)
        If value <> mCloseEnabled Then
            mCloseEnabled = value
            setSystemMenu()
        End If
    End Set
End Property
Private mCloseEnabled As Boolean = True

Protected Overrides Sub OnHandleCreated(ByVal e As System.EventArgs)
    MyBase.OnHandleCreated(e)
    setSystemMenu()
End Sub

Private Sub setSystemMenu()
    Dim menu As IntPtr = GetSystemMenu(Me.Handle, False)
    Dim enable As Integer
    If Not mCloseEnabled Then enable = 1
    EnableMenuItem(menu, SC_CLOSE, enable)
End Sub

'' P/Invoke declarations
Private const SC_CLOSE As Integer = &hf060
Private Declare Function GetSystemMenu Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal revert As Boolean) As IntPtr
Private Declare Function EnableMenuItem Lib "user32.dll" (ByVal hMenu As IntPtr, ByVal IDEnableItem As Integer, ByVal wEnable As Integer) As Integer