Ikky
Ikky

Reputation: 2856

C# Disable the TAB key

I have this code:

this.searchInput.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.inputKeypress);

private void Keypress(object sender, KeyPressEventArgs e)
{
    // If Tab has been pressed
    if(122 == (int)e.KeyChar)
    {
        switchTab(sTab);
        MessageBox.Show(sTab);
    }
}

What it does is that it sets focus to another element. But, when the focus is set to a TextBox, and I press TAB, it just makes a tab in the TextBox, and does not set focus on the next element.

Anyone got an idea how can I make this work?

I've tried to set e.Handled = true; but that didn't work...

Upvotes: 1

Views: 9545

Answers (3)

Irvingz
Irvingz

Reputation: 119

You'll need to create an instance of the control like so, and override the following methods:

using System.Windows.Forms

//optional namespace

public class NoTabTextBox : TextBox
{
    protected override bool IsInputKey(Keys keyData)
    {
        switch (keyData)
        {
            case Keys.Tab:
                return true;
        }
        return base.IsInputKey(keyData);
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab) { e.Handled = true; e.SuppressKeyPress = true; }
        base.OnKeyDown(e);
    }
}

Build the solution, then subsitute you're regular TextBox with the new one 'NoTabTextBox', by finding it under the user controls in toolbox.

This will capture the Tab key and force it to do nothing.

Upvotes: 2

Joren
Joren

Reputation: 14746

Have you tried setting AcceptsTab on the TextBox to false?

Edit:

yep. It does not work. Strange... It still tabulates in the textbox

That makes little sense. I ran a small test app, and the tab key only brings focus away from the TextBox when its AcceptsTab and Multiline properties are both true, regardless of an event handler being defined for KeyPress.

Are you sure some other code isn't setting AcceptsTab to true? If you are, does setting Multiline to false change the tab behaviour at all? Could you post more of your relevant code?

Upvotes: 6

RichieHindle
RichieHindle

Reputation: 281365

Set the AcceptsTab property of the text box to false?

Upvotes: 3

Related Questions