Intercept TAB key and suppress it
Asked Answered
S

1

15

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.

Siobhansion answered 6/5, 2012 at 11:7 Comment(3)
They are not fired because the TABkey is intended to be the key which moves focus to the next control, thus it has a special handling.Alternator
Thanks TLama. The behaviour is explained. So do you think, is there an escape route?Siobhansion
delphi.about.com/cs/adptips2002/a/bltip0702_5.htmSoandso
A
22

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.
Alternator answered 6/5, 2012 at 11:18 Comment(1)
Dear TLama, this worked just perfectly. Best cut&paste ever ;)Siobhansion

© 2022 - 2024 — McMap. All rights reserved.