C# - Override the Standard Windows Close Button to Pop-up my Custom Form -


yes, noob question. apologies.

when users click on red x button on window, want pop message asking if want quit. found similar question on site: override standard close (x) button in windows form.

the thing is, want customize font , messageboxicon messagebox, , sadly can't done (or take lot of effort done). so, i've decided make own form.

    protected override void onformclosing(formclosingeventargs e)     {         if (txtid.text != "" || txtpassword.text != "")         {             base.onformclosing(e);             if (e.closereason == closereason.windowsshutdown) return;              // confirm user wants close             new formconfirmexit().showdialog();         }     } 

i added code under main form. however, when run code , click on standard close button, pop (the custom form did) doesn't it's job. suppose click "no" button, terminates entire program. "yes" button, pop-up shows again, , kinda stops (on visual studio) , ta-da! exception.

btw, these yes , no button methods (from custom form's class):

    private void btnyes_click(object sender, eventargs e)     {         application.exit(); // terminate program (exception in here)     }      private void btnno_click(object sender, eventargs e)     {         this.close(); // close pop window , go main window     } 

changing application.exit() environment.exit(0) did job yes button, no button, well, terminates program, still.

edit: when click on yes button, pop-up/my custom form shows again (just 1 time). it'll stay on state (i can click on yes button repeatedly yet nothing happens). invalidoperationexception thrown when click yes button first (note first sentence of paragraph) no button.

thank you.

add in no_click:

private void btnno_click(object sender, eventargs e) {     dialogresult = dialogresult.no; } 

then, change forms closing event following:

protected override void onformclosing(formclosingeventargs e) {     if (txtid.text != "" || txtpassword.text != "")     {         base.onformclosing(e);         if (e.closereason == closereason.windowsshutdown             || e.closereason == closereason.applicationexitcall)                 return;          // confirm user wants close         using(var closeform = new formconfirmexit())         {             var result = closeform.showdialog();             if (result == dialogresult.no)                 e.cancel = true;            }     }        } 

first, checks if form isn't closing through application.exit(), may triggered other form, not reshow custom messagebox.

second, create using statement around custom form. way can preserve values. set dialogresult no, if user doesn't want cancel. if case, set e.cancel = true stop exiting.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -