3

There are lot of similar questions on here, but I couldn't find an answer for my problem.

I have a TRichEdit and want to implement some custom behaviour when the user presses Tab. I set the rich edit's WantTabs property to True and tried to add my custom behaviour in OnKeyDown, which works fine, but unfortunately after that the "normal" tab behaviour is executed as well (inserting a tab character in the edit). I tried setting Key to 0 in the event handler but that doesn't help.

How can I prevent the "normal" tab behaviour from being executed?

Joe
  • 2,805
  • 6
  • 38
  • 58
jpfollenius
  • 15,826
  • 9
  • 83
  • 148

1 Answers1

6

Use the OnKeyPress event instead:

procedure TForm1.RichEdit1KeyPress(Sender: TObject; var Key: Char);
begin
  if Key = chr(VK_TAB) then
  begin
    beep;
    Key := #0;
  end;
end;

Alternatively, if you really need to use the OnKeyDown event, simply remove the key messages:

procedure TForm1.RichEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  msg: TMsg;
begin
  if Key = VK_TAB then
  begin
    beep;
    while PeekMessage(msg, RichEdit1.Handle, WM_KEYFIRST, WM_KEYLAST,
      PM_REMOVE) do;
  end;
end;
Andreas Rejbrand
  • 95,177
  • 8
  • 253
  • 351
  • +1 thank you very much, that works! So, there seems to be some fundamental difference between `OnKeyPress` and `OnKeyDown`. Can you explain what this is? – jpfollenius Aug 18 '11 at 07:55
  • @Smasher: It is the key press that inserts the character. (If you press `VK_RIGHT`, you do get a key down and a key up (of course), but no key press, for there is no '`VK_RIGHT` character' inserted into the control.) – Andreas Rejbrand Aug 18 '11 at 07:57