IceCold
IceCold

Reputation: 21194

Modal dialog does not return focus to application

I have a custom control derived from TPanel named TTestCtrl. It holds a TImage32 (from Graphics32).

When the user double clicks on the image, I show a message. The problem is that after I close the message, the focus is not returned back to the main application. So, the first click, no matter what I click on in the main app/main form, is lost.

Strange thing: If I call the Mesaj() procedure not from the TTestCtrl but from the main form, it works (the first click is not lost anymore):

unit DerivedControl;

interface

uses
  System.SysUtils, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, Vcl.Forms, GR32, GR32_Image;

type
  TTestCtrl = class(TPanel)
  private
    Img: TImage32;
  protected
    procedure ChromaDblClick(Sender: TObject);
  public
    constructor Create(AOwner: TComponent); override;
  published
  end;

procedure Mesaj(const MessageText, Title: string);

implementation

procedure Mesaj(const MessageText, Title: string);
begin
{$IFDEF MSWINDOWS}
   Application.MessageBox(PChar(MessageText), PChar(Title), 0)  { 'Title' will appear in window's caption }
{$ELSE}
   MessageDlg(MessageText, mtInformation, [mbOk], 0);
{$ENDIF}
end;

constructor TTestCtrl.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  Width         := 200;
  Height        := 86;
  Img := TImage32.Create(Self);
  Img.Parent        := Self;
  Img.Align         := alClient;
  Img.OnDblClick    := ChromaDblClick;
end;

procedure TTestCtrl.ChromaDblClick(Sender: TObject);
begin
  Mesaj('Caption', 'From derived control');      // focus lost
end;

end.

The simple/minimal application below is the tester:

unit TesterForm;

interface

uses
  System.SysUtils, System.Classes, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.Controls, vcl.Forms, DerivedControl;

type
  TfrmTester = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
  public
  end;

var
  frmTester: TfrmTester;

implementation

{$R *.dfm}

var
  Ctrl: TTestCtrl;

procedure TfrmTester.FormCreate(Sender: TObject);
begin
  Ctrl := TTestCtrl.Create(Self);
  Ctrl.Parent := Self;
end;

procedure TfrmTester.Button1Click(Sender: TObject);
begin
  Mesaj('Caption', 'From main form');      // works
end;

end.

Upvotes: 1

Views: 1029

Answers (1)

Christophe Fardeau
Christophe Fardeau

Reputation: 224

Try this :

procedure TTestCtrl.ChromaDblClick(Sender: TObject);
var F : TcustomForm;
begin
  Mesaj('Caption', 'From derived control');      // focus lost
  F := GetParentForm(Self);
  if Assigned(F) then F.BringToFront;

end;

Upvotes: 1

Related Questions