lunedì 7 aprile 2014

VB.NET ESC button to close Form

It happened today that I was trying to close a form in a VB.NET application using the ESC key.
Usually if you have a Cancel button on the form or similar you can simply set the CancelButton property of the form to that button, but in my case I didn't have that button on the form nor I want to add one.

I tried using the KeyDown event, but, strange, pressing ESC or every other key didn't fire the event routine.

As I didn't have time to investigate and find out why it happened I preferred to search in internet for some easy and fast solution, I find one post from Adam Butler that worked,
it was in C# so I had to simply translate in VB.NET

here's the code to put in your form code to be closed:

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
        If (keyData = Keys.Escape) Then
            Me.Close()
            Return True
        End If

        Return MyBase.ProcessCmdKey(msg, keyData)
    End Function

Nessun commento:

Posta un commento