Visually remove/disable close button from title bar .NET

Jrud picture Jrud · Nov 16, 2009 · Viewed 86.7k times · Source

I have been asked to remove or disable the close button from our VB .NET 2005 MDI application. There are no native properties on a form that allow you to grey out the close button so the user cannot close it, and I do not remember seeing anything in the form class that will allow me to do this.

Is there perhaps an API call or some magical property to set or function to call in .NET 2005 or later to do this?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

More information:

I need to maintain the minimize/maximize functionality

I need to maintain the original title bar because the form's drawing methods are already very complex.

Answer

Philip Wallace picture Philip Wallace · Nov 16, 2009

Based on the latest information you added to your question, skip to the end of my answer.


This is what you need to set to false: Form.ControlBox Property

BUT, you will lose the minimize and maximize buttons as well as the application menu (top left).

As an alternative, override OnClose and set Cancel to true (C# example):

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (e.CloseReason != CloseReason.WindowsShutDown && e.CloseReason != CloseReason.ApplicationExitCall)
    {
        e.Cancel = true;
    }

    base.OnFormClosing(e);
}

If neither of these solutions are acceptable, and you must disable just the close button, you can go the pinvoke/createparams route:

How to disable close button from window form using .NET application

This is the VB version of jdm's code:

Private Const CP_NOCLOSE_BUTTON As Integer = &H200
Protected Overloads Overrides ReadOnly Property CreateParams() As    CreateParams
   Get 
      Dim myCp As CreateParams = MyBase.CreateParams 
      myCp.ClassStyle = myCp.ClassStyle Or CP_NOCLOSE_BUTTON 
      Return myCp 
   End Get 
End Property