views:

415

answers:

3

Hi, I need custom behavior for tab keys in RichTextEdit control.

Currenty the best I have is this:

editBox.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.field_PreviewKeyPress);


  private void field_PreviewKeyPress(object sender, PreviewKeyDownEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Tab: 
                     //Some code here
                break;
            }
        }

The tab key is registered fine, but after that the control processes the key anyway and moves the focus to next control. There seems no way to consume this key event.

A: 

You say you're using a "RichTextEdit" control but I guess you mean RichTextBox. If so, you should be able to set the AcceptsTab property to True to allow it to process the tab key.

Matt Hamilton
Unfortunately this only works for multiline RichTextBox.
extropy
Really? How interesting! I'll leave the answer here so that others who read it can see your comment and learn why it's *not* the answer.
Matt Hamilton
+1  A: 

Maybe this CodeProject article could give you some hint:

TabKeyIntercept - Intercept and process the Tab key in a Windows.Forms form

[...] Fortunately, in the base Form class, there exists the protected override bool ProcessTabKey(bool forward) method. Using this method, we can intercept and "consume" the Tab key.

And, as it turns out, if the ProcessTabKey() method's return value is false, the Tab key does make it into the OnKeyDown() method. But, of course, if your code "consumes" the Tab key in the ProcessTabKey() method, you probably won't need to process it in the OnKeyDown() method.

Also, the Control-Tab combination makes it into the OnKeyDown() method.

So, knowing these things, we are prepared to define a customized use for the Tab key -- and we can code the form to allow the user to use the Control-Tab combination to toggle between the normal use/meaning of the Tab key and our custom use.

splattne
ProcessTabKey is Form method. It would be very clumsy to have a custom form, just to alter behavior of one field .
extropy
+1  A: 

Found a solution myself - override bool RichTextEdit.ProcessCmdKey(ref Message m, Keys keyData).

extropy