Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Disabling Close Button on Forms

0.00/5 (No votes)
12 Sep 2007 1  
How to disable the Close button on C# WinForms
Screenshot - TestForm.gif

Introduction

To prevent the user from closing the form during data processing, it would be good if we disable the Close button on the form. Whenever it is required to show such a form with the Close button disabled, the first step is to look into the properties of the form to find the corresponding property. But I have found that form does not have such a kind of property provided by VS.NET/C#. Hence we need to do it programmatically and this article presents how to do it.

Background

In one of my projects, I had to implement a form with Close button disabled, so that the user cannot leave the form until it finishes the data processing. From the form designer window in VS.NET 2005, it is possible to hide the Minimize box and Maximize box. But there is no property called Close or Show close. Then I had some discussions with the team mates and got a couple of ways to do this. Among those alternatives, finally my idea got the nod. I thought of sharing this idea with The Code Project community and hence I have written this small article.

Using the Code

During construction and creation of the Form object, .NET would use the default creation parameters available in the base class CreateParams property. In fact, CreateParams property is available in Forms.Control class. In our form class (derived from System.Windows.Forms.Form), override this property and modify the creation flags. For disabling the Close button use 0x200 to modify the ClassStyle member of the CreateParams.

//
// source code 
// Code Snippet
 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;
     }
 } 

That's it! We are done with the coding.

Points of Interest

The trick here is to override the CreateParams property in our Form with modified create flags. Directly copy the above piece of code and paste it to your Form class and it should work. Happy coding!!!

History

  • 7th September, 2007: Initial version created

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here