Correct way to do this

sgt_pinky

Regular
Joined
Jan 5, 2005
Messages
80
Location
Melbourne, Australia
Hi,

What is the correct way to do this. I have a windows forms app, and I want several of the forms to close when I press escape.

So I have the general sub-routine in say 6 different forms, all with the same code:

Visual Basic:
    Private Sub CloseFormOnEscape(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cmbSkin.KeyPress
        If Asc(e.KeyChar) = Keys.Escape Then Me.Close()
    End Sub

In order to make my app more manageable, I could put the one subroutine in a general class, and just use AddHandler in the Form_Load() sub of each form.

I was wondering if there was some better way that I could do it, using Inherits or something like that.

This is a simple example, the actual code that I want to do this with is a class that is used to drag a skinned form, based on some specific controls.

Cheers,

Pinky
 
I'm slightly confused, the first time I read your post I thought that with a single press of escape you wanted to close several forms. But the second time I read it I just got the impression you wanted several forms with similar behaviour to each other, closing each one individually when escape is pressed. If the latter is true then as you can say this could be handled by either attaching events in the manner your doing or by inheritance.

To do the inheritance method you simply create a class (called ExtendedForm or something) that inherits from System.Windows.Form and add/override key events. Then any form you wish to have this behaviour you inherit from MyNamespace.ExtendedForm rather than System.Windows.Form.
 
If you are displaying them with the .ShowDialog Method simplyset a button on the form to be the cancel button and it will close automatically when escape is hit.
 
Back
Top