Jul 24, 2012

Disable close button on form - C#

1 comment
In one of my projects, I had to implement a form with Close[X] button Hide, 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 CloseBox.

Then I had tried with by setting form property ControlBox = false. With this i am able to achieve hiding the Close/Minimize/Maximize buttons. But at the same time there is a side effect.i.e., Form icon(which is generally displayed on form title bar)  also hidden. 

So after little bit investigation came up with the following hack to get,
 i)  disable the close button
 ii) displaying the form icon
To achieve this, we have to override CreateParams property of Form base class as follows,

Code:
        private const int CP_DISABLE_CLOSE_BUTTON = 0x200;
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams mdiCp = base.CreateParams;
                mdiCp.ClassStyle = mdiCp.ClassStyle | CP_DISABLE_CLOSE_BUTTON;
                return mdiCp;
            }
        }

That's it.

If you feel this is helpful or you like it, Please share this using share buttons available on page.

1 comment :