Shambhala
Shambhala

Reputation: 1169

How to keep Modal Dialog on top of Dynamic Created Form? (CreateParams - overridden)

I am dynamically creating a Form that overrides the CreateParams so that I can have it displayed on the TaskBar. From the dynamically created Form, I am calling a TColorDialog but once it is displayed my Form will go under the MainForm with the ColorDialog on top of that.

After the ColorDialog is closed the dynamic Form will return back over the MainForm.

I see that on the ColorDialog Execute method there is a Handle that can be passed but I am not sure if I am on the right track with that?

If I click under the Dialog on the MainForm it will flash but how can I have the dynamically created Form "own" this Dialog with the MainForm at the back?

I create the Form like this:

procedure TMain.Button1Click(Sender: TObject);
var
  SEMArcF: TWriteSEMArcFrm;
begin
  SEMArcF := TWRiteSEMArcFrm.Create(nil);
  SEMArcF.Show;
end; 

and it is freed on the OnClose Event:

procedure TWriteSEMArcFrm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;
end;

I am overriding the CreateParams like this:

procedure TWriteSEMArcFrm.CreateParams(var Params: TCreateParams);
begin
  inherited;
  if (FormStyle = fsNormal) then begin
    Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
    Params.WndParent := GetDesktopWindow;
  end;
end;

and to show the ColorDialog I either create it or just have a TColorDialog Component on the Form, either way will result in the same. I want it to be owned by the dynamic Form.

EDIT I now add:

Application.ModalPopupMode := pmAuto;

The full code:

procedure TWriteSEMArcFrm.btnBackColourClick(Sender: TObject);
var
  ColorDlg: TColorDialog;
begin
  Application.ModalPopupMode := pmAuto;
  ColorDlg := TColorDialog.Create(nil);
  try
    if ColorDlg.Execute then
    re.Color := ColorDlg.Color;
  finally
    ColorDlg.Free;
  end;
end;

This works fine but could there be any unusual behaviour by setting this?

Thank you

Chris

Upvotes: 2

Views: 896

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595295

TColorDialog derives from TCommonDialog, which has two overloaded versions of Execute() available - the legacy parameterless version that has existed for years, and a newer overload that takes a parent HWND as an input parameter. You are likely calling the former. That overload uses the Handle property of the currently active TForm (only if the TApplication.ModalPopupMode property is not set to pmNone), falling back to the Handle of the MainForm if needed. If you want more control, you should call the other overload directly instead, then you can pass the dynamic form's Handle property as the parameter value.

Upvotes: 8

Related Questions