c winform cancels the implementation of the close button in the upper right corner

  • 2020-05-19 05:38:41
  • OfStack

One way to do this is to set the form's ControlBox property to false in the properties panel of the form, or to write this in the form's constructor:


public Form1()

{

InitializeComponent();

this.ControlBox = false;   //  Set the close button not to appear 

}

However, if you do this, both the minimize and maximize buttons will be removed, so if you want to just disable the close button and keep the minimize and maximize, override the CreateParams method of the form:

// Disable the close button for the form 

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;

}

}

Or cancel the close event execution in the upper left corner

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
//  rewrite OnClosing Enables the form to indent into the tray when the close button is clicked 
protected override void OnClosing(CancelEventArgs e)
{
this.ShowInTaskbar = false;
this.WindowState = FormWindowState.Minimized;
e.Cancel = true; 
} 


Related articles: