如何禁用如下图所示表单的关闭按钮?(下图显示一个MessageBox
窗口)
以上是我生成的MessageBox
!我想禁用普通表单的关闭按钮。
右键单击有问题的窗口,然后单击属性。在属性下单击事件。双击FormClosing
事件。
以下代码将由 Windows 窗体设计器生成:
private void myWindow_FormClosing(object sender, FormClosingEventArgs e)
{
}
只需将代码更新为如下所示(添加e.Cancel = true;
):
private void myWindow_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
你完成了!
或者,如果您想禁用窗口的关闭、最大化和最小化按钮:
您可以右键单击有问题的窗口,然后单击属性。在属性下将属性设置ControlBox
为false
。
如果您正在使用 MDI 子窗口,并且在创建窗口期间禁用关闭按钮被排除在外(即您想在表单生命周期的某些时间禁用它),那么之前提出的解决方案都不会起作用¹。
相反,我们必须使用以下代码:
[DllImport("user32")]
public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32")]
public static extern bool EnableMenuItem(IntPtr hMenu, uint itemId, uint uEnable);
public static void DisableCloseButton(this Form form)
{
// The 1 parameter means to gray out. 0xF060 is SC_CLOSE.
EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 1);
}
public static void EnableCloseButton(this Form form)
{
// The zero parameter means to enable. 0xF060 is SC_CLOSE.
EnableMenuItem(GetSystemMenu(form.Handle, false), 0xF060, 0);
}
¹您可以设置ControlBox = false
是否不需要任何按钮,但这不是问题所在。
您处理 Form 的Closing事件(而不是 Closed 事件)。
然后你使用 e.CloseReason 来决定你是否真的要阻止它(UserClose)或不(TaskManager Close)。
此外,还有一个小例子,在codeproject上的 Forms上禁用关闭按钮。
您应该覆盖CreateParams
派生自的函数System.Windows.Forms.Form
并改变班级风格
myCp.ClassStyle = 0x200;
Closing += (s, eventArgs) =>
{
DialogResult = DialogResult.None; //means that dialog would continue running
};