Capture tab key

csharp United States
  • 19 years ago

    I have tried the KeyDown, KeyPress and KeyUp events but they don't capture the pressing of the Tab key.  Anyone know of how to capture the event when the Tab key is pressed?

  • 19 years ago

    The following code works with the KeyPress event!


    Private Sub Form_KeyPress(KeyAscii As Integer)
       If KeyAscii = 9 Then
           MsgBox "Tab Key pressed!"
       End If


    End Sub

  • 19 years ago

    The only way I have been able to capture the tab key from a Windows Form textbox is to set AcceptTabs=true and Multiline=true but this makes the tab part of the input text which I don't want to do.  Maybe your code works on a web page form and that is the difference.  I was able to solve my problem by accessing the Leave event.  The text box was part of a user control that included a drop down list and this way the drop down list could be closed automatically whether you pressed tab or clicked into another text box control.  Thanks for your input.  I am curious if your code worked for you because of AcceptTabs and Multiline settings or because it was on a web form.  I would appreciate it if you could fill me in.  Thanks again.


    Kyle


  • 19 years ago

    I searched everywhere I could think of and couldn't find the syntax for overriding the ProcessDialogKey method.  I finally looked at online help and it turned out to be really simple.


    Here's the story:


    In the online help it shows this syntax:


    [C#]
    protected override bool ProcessDialogKey(Keys keyData);


    Create the method as follows:


    protected override bool ProcessDialogKey(Keys keyData)
    {
       MessageBox.Show("Override: " + keyData);
       base.ProcessDialogKey(keyData);
       return true;
    }


    This method intercepts and processes keys that are not intercepted by the KeyPress event.


    base.ProcessDialogKey(keyData) takes the keyData and processes it as if it had not been intercepted.  For example with this override in place if you press the tab key when your cursor is in a text box the override method will fire, the MessageBox will show and then the base.ProcessDialogKey will continue with normal operation of the tab moving you to the next control.  If you press the shift key, as you would expect the override fires but the base process leaves the cursor in the text box.


    This all seems so simple once you know it and such a mystery when you don't.


    One more mystery put to rest.


    Kyle

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Never trust a programmer in a suit.” - Anonymous