我如何禁用一个窗体的关闭按钮,就像下面这张图片中显示的那样?(下面的图片展示了一个MessageBox
窗口)
上面的MessageBox
是由我生成的!我想要禁用普通窗体的关闭按钮。
我如何禁用一个窗体的关闭按钮,就像下面这张图片中显示的那样?(下面的图片展示了一个MessageBox
窗口)
上面的MessageBox
是由我生成的!我想要禁用普通窗体的关闭按钮。
右键单击所涉及的窗口,然后单击“属性”。 在属性下单击“事件”。 双击“FormClosing”事件。
Windows Form Designer将生成以下代码:
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
,但这并不是问题所问的。
myCp.ClassStyle = 0x200;
Closing += (s, eventArgs) =>
{
DialogResult = DialogResult.None; //means that dialog would continue running
};