delphidelphi-xe

How to override TTabControl OnKeyDown?


I have a TTabControl on a form, and I would like that if the tabs (tab header) is focused, and when the user presses Ctrl+RightArrow, it will focus on the right-most tab. Sadly, TTabControl doesn't have an OnKeyDown event, unlike TEdit. How can I implement a custom OnKeyDown event?


Solution

  • You can subclass the TabControl's WindowProc property to do whatever you want with its received messages directly, eg:

    type
      TMyForm = class(TForm)
        TabControl1: TTabControl;
        ...
        procedure FormCreate(Sender: TObject);
        ...
      private
        OldTabWndProc: TWndMethod;
        procedure MyTabWndProc(var Message: TMessage);
        ...
    end;
    
    procedure TMyForm.FormCreate(Sender: TObject);
    begin
      OldTabWndProc := TabControl1.WindowProc;
      TabControl1.WindowProc := MyTabWndProc;
    end;
    
    procedure TMyForm.MyTabWndProc(var Message: TMessage);
    begin
      if Message.Msg = WM_KEYDOWN then
      begin
        ...
      end;
      OldTabWndProc(Message);
    end;