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.
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
private const int CP_NOCLOSE_BUTTON = 0x200;
protected override CreateParams CreateParams
CreateParams myCp = base.CreateParams;
myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON ;
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!!!
- 7th September, 2007: Initial version created