Home How to get the focused/selected object in delphi?
Reply: 1

How to get the focused/selected object in delphi?

Sonocronic
1#
Sonocronic Published in 2018-02-13 11:59:04Z

I have a PageControl object with several pages in separate tabs. Each tab contains a lot of objects such as TEdits and TComboBoxes. Lets say I'm in "Tab A" entering text in a TEdit and then the software change tab to "Tab B" and then back to "Tab A". Then the TEdit is no longer selected so I need to select it again to continue writing.

Now to my question: How can I save/get/store the selected object before change of tab so that I can return to the same object when back to the previous tab?

Thanks!


2018-02-15 Update:

Thanks @ExDev!

Screen.ActiveControl was what I where looking for! I solved it like this:

Var FocusObject : TWinControl;

// Save selected object
FocusObject:= Screen.ActiveControl;

// Restore selected object
FocusObject.SetFocus;

ExDev
2#
ExDev Reply to 2018-02-13 13:30:52Z

You could use the TPageControl.OnChanging event to store the focused control before changing the active tab and the TPageControl.OnChange event to restore its focused state.

Example:

TForm1 = class(TForm)
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    Edit4: TEdit;
    procedure PageControl1Changing(Sender: TObject; var AllowChange: Boolean);
    procedure FormCreate(Sender: TObject);
    procedure PageControl1Change(Sender: TObject);
  private
    FActiveControls : array of TWinControl;
  end;

...

procedure TForm1.FormCreate(Sender: TObject);
begin
  SetLength(FActiveControls, PageControl1.PageCount);
end;

procedure TForm1.PageControl1Change(Sender: TObject);
begin
  if(FActiveControls[TPageControl(Sender).ActivePageIndex] <> nil)
  then FActiveControls[TPageControl(Sender).ActivePageIndex].SetFocus();
end;

procedure TForm1.PageControl1Changing(Sender: TObject;
  var AllowChange: Boolean);
begin
  FActiveControls[TPageControl(Sender).ActivePageIndex] := Screen.ActiveControl;
end;

Note:

Both events are not called if you change the active page in code, for example, by setting the value of TPageControl.ActivePage.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305958 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO