13

I need to intercept the TAB keyboard stroke on TEdits and suppress them programmatically. In certain cases I don't want the focus to change to the next control.

I tried to handle KeyPress, KeyDown both on TEdit level and on TForm with KeyPreview=true. I've peeked advices from:

But it didn't work. The events are fired for, let's say, the Enter key BUT not for the TAB key.

I'm using Delphi 7. Thanks for your help.

Community
  • 1
  • 1
Jako
  • 2,210
  • 3
  • 26
  • 35
  • They are not fired because the `TAB`key is intended to be the key which moves focus to the next control, thus it has a special handling. – TLama May 06 '12 at 11:11
  • 1
    Thanks TLama. The behaviour is explained. So do you think, is there an escape route? – Jako May 06 '12 at 11:15
  • 1
    http://delphi.about.com/cs/adptips2002/a/bltip0702_5.htm –  May 06 '12 at 11:18

1 Answers1

18

If you want to intercept the TAB key behavior, you should catch the CM_DIALOGKEY message. In this example, if you set the YouWantToInterceptTab boolean value to True, the TAB key will be eaten:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
  private
    YouWantToInterceptTab: Boolean;
    procedure CMDialogKey(var AMessage: TCMDialogKey); message CM_DIALOGKEY;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.CMDialogKey(var AMessage: TCMDialogKey);
begin
  if AMessage.CharCode = VK_TAB then
  begin
    ShowMessage('TAB key has been pressed in ' + ActiveControl.Name);

    if YouWantToInterceptTab then
    begin
      ShowMessage('TAB key will be eaten');
      AMessage.Result := 1;
    end
    else
      inherited;        
  end
  else
    inherited;
end;

end.
TLama
  • 71,521
  • 15
  • 192
  • 348