Friday, August 26, 2011

CancelButton & AcceptButton - Programming tips & tricks

CancelButton & AcceptButton - Programming importance and ease!

Ever wondered to write code that will do something (like form exit, etc.) on pressing "Escape" key?

Ever wondered to write code that will do something (like form submit, OK, etc.) on pressing "Enter" key?


Setting the Form's "CancelButton" & "AcceptButton" property is right way to go.

Brief Steps:

Lets see the Escape button thing first:

1. Set the Form's "CancelButton" property to the name of a button (say, btnCancel)
2. Write the "btnCancel" button's click even-handler (code-behind could be in C#.NET, VB.NET, etc.)
3. Build and Run, press "Escape" key on keyboard, to see the output
Thats all!

Similarly, write code for "AcceptButton" property that works for "Enter" key, by attaching to OK or Submit button

Detailed Steps:

1. Create a new button with:
"Name" property as cancelButton (or, exitButton, etc.), and
"Caption" property as "Cancel"

(of course, if you have an existing button to that you can use, then nothing to do, skip to step#2, and use your button where ever "cancelButton" is mentioned below)

2. Select the buttonCancel button (or, your button) on the form, in the designer, double-click it, to write its "click" event handler

For example:

Write below code to show message box at run-time (C# code)

// puts a message box to user
MessageBox.Show("caught Escape key, Do you want to exist? etc.");

Write below code, to close the form at run-time (C# code)

// closes the form

3. Select the Form, in designer, right-click Properties (or, press F4 key), set the "CancelButton" property to buttonCancel (or, name of your button)

4. Build (Ctrl+B key combination) and run (Ctrl+F5 key combination)

5. Press "Escape" key

Depending on what you chose to write in 2.a) or 2.b) or both, you will see a message box, or form will exit, or both

Thats all!


Easy code maintenance

If you created a new control on form, then nothing more you need to code
The same code works
No worries about where the focus is, or writing escape key handler to all the controls, or mapping to same event-handler - not even to your would-be new controls

In other ways, of handling escape key (key codes, key enumerations, etc.), you may need to write new or map to existing handler,
i.e; Assume that there are 50 controls, then 50 control's property you should go and edit, which is an obvious futile attempt - also in terms on your health/ hand pain/ mental stress

Setting CancelButton property once, will take care of ESCAPE key, for Form and all its child controls
Setting AcceptButton property once, will take care of ENTER key, for Form and all its child controls

Of course, if you want to set a different functionality/event-handler for some control on the form, if/when it is focused.

If you like this post, please add below link to your site: