Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling the exit button on a windows form?

Tags:

c#

.net

winforms

Is there a way to disable the exit button on a windows form without having to import the some external .dll's? I disable the exit button by importing dll's 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'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);
    }
like image 390
Kredns Avatar asked Oct 27 '25 06:10

Kredns


1 Answers

To disable the close button on the form just write the below code on the form closing event.

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
    }
like image 84
Saran N V Avatar answered Oct 28 '25 21:10

Saran N V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!