Disabling a window-shaped exit button?

Is there a way to disable the exit button on a Windows form without having to import some external .dll? I will disable the exit button by importing the dll using the following code, but I don't like it. Is there a simpler (built-in) way?

    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 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);
    }
+3
source share
7 answers

A little banter found this convenient class of helpers:

Disable the Close button and prevent the form from moving (C # version)

This is actually more than what you are looking for, but essentially does it in much the same way as in your code example. The helper class connects to load / resize events for you, so you need to remember to do it yourself.

+4

( , ).

, ControlBox false.

ControlBox , , , .

FormClosing , .

.

Windows Forms.

CheckBox "ControlBox". 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;
}

. , .

+5

, .

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

.

. ControlBox = false . , .

form.FormBorderStyle = FormBorderStyle.None, .

X, , OnClosing e.Cancel true.

+3

FormClosing .

+2

, , ControlBox false this.ControlBox = false; frmMainForm.ControlBox = false;

+1
source

Disabling a button is possible without importing the DLL. ControlBox = falsecauses minimization and maximization of buttons, and the border also disappears, and it does not disable the closed "X" button - it is hidden. This solution disables it:

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;
    }
}

Source: https://www.codeproject.com/kb/cs/disableclose.aspx

0
source

Source: https://habr.com/ru/post/1705377/


All Articles