stillLearning
stillLearning

Reputation: 170

How to get the currently active form in my application?

How to get the currently active (focused) form in my application?

Upvotes: 15

Views: 15370

Answers (3)

Core
Core

Reputation: 618

This code worked fine for me, no global variable is required and each form NAME is unique because Delphi IDE is not accepting duplicate form name.

if Screen.ActiveForm.Name = Self.Name then
begin
    // Do your work here
end

I used this code to close form when ESC button is pressed on keyboard and only active/current form should be closed.

Here is the example:

if Msg.message = WM_KEYDOWN then
  begin
    if Msg.wParam = Ord(VK_ESCAPE) then
    begin

      if Screen.ActiveForm.Name = Self.Name then
      begin

        if (MessageDlg('DO YOU WANT TO CLOSE ' + UpperCase(Self.Caption) + ' FORM?',
          mtConfirmation, [mbYes, mbNo], 0) in [mrYes]) then
        begin
          Close;
        end;

      end;

    end;

  end;

Upvotes: 1

Jens Borrisholt
Jens Borrisholt

Reputation: 6402

Screen.ActiveForm does the trick.

Upvotes: 17

user7493939
user7493939

Reputation:

You can code the following ways :

   var CurrentForm: TForm; // Make sure to make it a global variable

  procedure KeyDownEvents(var Key: Word; Shift: TShiftState);
    begin
    CurrentForm:=Screen.ActiveForm.Name;
    if Key = VK_F9 then CurrentForm.KeyBoard1.Show;
    end;

This will fix the issue. Similarly you can handle the form on mouse click and other key press. Hope this helps.

Upvotes: 3

Related Questions