简体   繁体   中英

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?

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.

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

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(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM