Toby Smith
Toby Smith

Reputation: 1605

Is it possible to disable the "close" button while still being able to close from elsewhere?

I have a winforms application where I want the close button in the top-right corner of the program to instead minimize the program.

I have been able to achieve this by using the form's FormClosing event like this:

this.Hide();
e.Cancel = true;

But this unfortunately also stops any other close buttons I place on the form.

Is there a way to only stop the default button in the top-right but still be able to close the form elsewhere?

Upvotes: 1

Views: 166

Answers (3)

Idle_Mind
Idle_Mind

Reputation: 39132

Another way to disable the "X" in the top right:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    protected override CreateParams CreateParams
    {
        get
        {
            const int CS_NOCLOSE = 0x200;
            CreateParams cp = base.CreateParams;
            cp.ClassStyle |= CS_NOCLOSE;
            return cp;
        }
    }

}

The form can still be closed programmatically with this.Close();.

Upvotes: 0

Travis Boatman
Travis Boatman

Reputation: 2282

This is a simple boolean example:

bool ExitApplication = false;

private void Form1_FormClosing(Object sender, FormClosingEventArgs e) 
{
    switch(ExitApplication)
    {
      case false:
      this.Hide();
      e.Cancel = true;
      break;

      case true:
      break;
    }
}

So when you want to close your application just set ExitApplication to true.

Upvotes: 2

M. Nasir Javaid
M. Nasir Javaid

Reputation: 5990

Use this to disable close button from your form at top right corner.

 public partial class Form1 : Form
 {
    const int MfByposition = 0x400;
    [DllImport("User32")]
    private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
    [DllImport("User32")]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    [DllImport("User32")]
    private static extern int GetMenuItemCount(IntPtr hWnd);
    public Form1()
    {
        InitializeComponent();
        var hMenu = GetSystemMenu(Handle, false);
        var menuItemCount = GetMenuItemCount(hMenu);
        RemoveMenu(hMenu, menuItemCount - 1, MfByposition);
        ...
    }
}

Upvotes: 0

Related Questions