Receive Tab Key...

BlackStone

Regular
Joined
Jun 14, 2004
Messages
75
I am writing a custom control, and I was wondering how I could capture the Tab key. I am sure it is a fairly common problem, but I could not seem to find it on google.
 
Windows. Also, it seems the arrow keys aren't being captured either.

Edit: Moved to correct forum
 
Last edited by a moderator:
How are you trying to capture these keys? Do you have any existing code?
You will probably find that you want to try either the KeyUp or KeyDown events rather than the KeyPress event.
 
BlackStone said:
would I have to do something so dramatic?? There is no way I can just set an option somewhere?

I just suggested this because you expressed major interest in keypresses. This being the case i assumed you might be doing something that would warrant this. As for the Tab, i'm unsure how to trap it.
 
What code do you have in the event handler? If you wish to prevent the tab key performing it's default action you will also need to set e.Cancel = true from within the event handler.
 
I don't think KeyPress has a Cancel argument? Ok, you can use 'e.Handled = True'. There's still a problem in that the {Tab} key seems to be handled before the Keypress ever arrives at the control and therefore moves focus to the next control without any Control_KeyPress() events firing at all.

I think you need to either:

(1) Set the .TabStop properties for the Controls in question = False, or

(2) Set the Form.KeyPreview property = True, allowing you to trap/process the {Tab} keys there.

I think that idea #1 is easier to implement though.
 
One of the properties of both TextBox & RichTextBox is AcceptsTab, and I am looking to implement such functionality in my own custom control, which means I don't want the user to have to change the tabstop of every one of the other controls on the same form.

Here i just an example of what I am looking for:
Code:
_
    public class Example : Control
    {
        public Example()
        {

        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.KeyData == Keys.Tab)
            {
                // Won't ever reach this point.
                // How can I fix that?
                MessageBox.Show("Tab caught!");
            }
            else if (e.KeyData == Keys.A)
            {
                MessageBox.Show("The letter a is caught!");
            }
        }
    }
 
Certain keys, such as Tab get special processing. Because of this, they never reach OnKeyDown. To disable the special processing, you can override ProcessDialogKey and return False for the keys in question:
Code:
    Protected Overrides Function ProcessDialogKey(ByVal keyData As System.Windows.Forms.Keys) As Boolean
        If keyData = Keys.Tab Then
            Return False
        Else
            Return MyBase.ProcessDialogKey(keyData)
        End If
    End Function

After you do that, they'll reach OnKeyDown just like any other key.
 
Back
Top