Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept TAB key and suppress it

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:

  • Intercept TAB key in RichEdit
  • How do I make the TAB key close a TComboBox without losing the current position?

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.

like image 585
Jako Avatar asked May 06 '12 11:05

Jako


1 Answers

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.
like image 55
TLama Avatar answered Sep 23 '22 17:09

TLama