如何在Visual Basic中的代码中禁用X按钮

问题描述

我想根据条件在表单上禁用X按钮。 像这样:

If Boolean Then 
   ControlBox = False
Else
   ControlBox = True
End If

当我尝试使用它时,我收到一条错误消息,说Visual Basic不支持功能。 这将在表单加载时完成,布尔值将保持不变。

我已经搜索过该论坛,但找不到适合我需求的答案。

谢谢。

解决方法

您似乎正在尝试在运行时设置ControlBox属性。如您所见,您不能这样做。但是,只需一点API魔术,您就可以完成此任务:

Option Explicit

Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long,ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long,ByVal nIndex As Long,ByVal dwNewLong As Long) As Long
Private Declare Function SetWindowPos Lib "user32" (ByVal hWnd As Long,ByVal hWndInsertAfter As Long,ByVal X As Long,ByVal Y As Long,ByVal cx As Long,ByVal cy As Long,ByVal wFlags As Long) As Long

Private Const WS_SYSMENU = &H80000
Private Const GWL_STYLE = (-16)
Private Const SWP_FRAMECHANGED = &H20
Private Const SWP_NOMOVE = &H2
Private Const SWP_NOZORDER = &H4
Private Const SWP_NOSIZE = &H1

Private Property Let ControlBoxVisible(ByVal Value As Boolean)
   Dim style As Long
   
   style = GetWindowLong(Me.hWnd,GWL_STYLE)
   style = IIf(Value,style Or WS_SYSMENU,style And Not WS_SYSMENU)
   SetWindowLong Me.hWnd,GWL_STYLE,style
   SetWindowPos Me.hWnd,SWP_FRAMECHANGED Or SWP_NOMOVE Or SWP_NOZORDER Or SWP_NOSIZE
End Property

然后您将像这样使用它:

Private Sub Form_Load()
   ControlBoxVisible = False
End Sub
,

使用API​​调用。 看看Enable / Disable Forms Close Button

有一个带有源代码的压缩项目文件。