winform removes the approach to the upper right corner close button

  • 2020-06-12 10:31:20
  • OfStack

1 you can set the ControlBox property of the form to false in the properties panel of the form, or write this in the constructor of the form:


public Form1()
{
InitializeComponent();
this.ControlBox = false;   //  The close button does not appear 
}

Doing so, however, removes both the minimize and maximize buttons, so if you want the close button to not work and the minimize and maximize buttons to remain, 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: