禁用Windows窗体上的退出按钮?

时间:2009-03-26 02:10:30

标签: c# .net winforms

有没有办法在Windows窗体上禁用退出按钮而无需导入某些外部.dll?我通过使用以下代码导入dll来禁用退出按钮,但我不喜欢它。是否有更简单的(内置)方式?

    public Form1()
    {
        InitializeComponent();
        hMenu = GetSystemMenu(this.Handle, false);
    }

    private const uint SC_CLOSE = 0xf060;
    private const uint MF_GRAYED = 0x01;
    private IntPtr hMenu;

    [DllImport("user32.dll")]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

    [DllImport("user32.dll")]
    private static extern int EnableMenuItem(IntPtr hMenu, uint wIDEnableItem, uint wEnable);

    // handle the form's Paint and Resize events 

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        EnableMenuItem(hMenu, SC_CLOSE, MF_GRAYED);
    }

    private void Form1_Resize(object sender, EventArgs e)
    {
        EnableMenuItem(hMenu, SC_CLOSE, MF_GRAYED);
    }

7 个答案:

答案 0 :(得分:5)

您无法轻松禁用退出按钮(右上角关闭表单的按钮)。

但是,您可以通过将ControlBox属性设置为false来完全隐藏按钮。

ControlBox可以随时打开和关闭,因此如果您想在某些时候动态允许关闭,而不是在其他时间关闭,则可以使用此项。

或者,您可以处理FormClosing事件并在您选择时取消关闭。

这是一个演示。

创建一个新的Windows窗体项目。

使用Text“ControlBox”在表单上删除CheckBox控件。将其Click事件连接到此:

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    ControlBox = checkBox1.Checked;
}

然后,使用文本“取消关闭”在表单上删除第二个CheckBox控件。将表单的FormClosing事件连接到此:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = checkBox2.Checked;
}

运行应用程序并开始使用复选框。你很快就会看到事情是如何运作的。

答案 1 :(得分:5)

要禁用表单上的关闭按钮,只需在表单结束事件上写下以下代码。

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
    }

答案 2 :(得分:4)

有点蠢蠢欲动地发现了这个方便的助手类:

Disable Close Button and Prevent Form Being Moved (C# version)

它实际上比你正在寻找的更多,但基本上它与你在示例代码中的方式非常相似。帮助程序类为您挂钩加载/调整大小事件,因此您不必记住自己执行此操作。

答案 3 :(得分:3)

是。

设置form.ControlBox = false将隐藏关闭按钮。虽然,它也会隐藏最小化和最大化按钮。

您还可以设置form.FormBorderStyle = FormBorderStyle.None,这将隐藏整个标题栏。

如果要显示X按钮但只是停止关闭表单,请覆盖OnClosing并将e.Cancel属性设置为true。

答案 4 :(得分:2)

捕获FormClosing事件并在参数中取消它。

答案 5 :(得分:1)

使用visual studio选择表单转到属性并将ControlBox属性设置为false或尝试this.ControlBox = false;frmMainForm.ControlBox = false;

答案 6 :(得分:0)

无需导入dll即可禁用该按钮。 ControlBox = false导致最小化和最大化按钮,边框也会消失,并且不会禁用关闭的“X”按钮 - 它会隐藏。此解决方案禁用它:

private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams
{
    get
    {
       CreateParams myCp = base.CreateParams;
       myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON ;
       return myCp;
    }
}

来源:https://www.codeproject.com/kb/cs/disableclose.aspx