unit MyDialogHandle;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    ReplaceDialog1: TReplaceDialog;
    OpenDialog1: TOpenDialog;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  WndProcPtrAtom: TAtom;  // Replace Dialogs private global!

implementation

{$R *.dfm}

// BeginExample: DialogHandle
// Property: Forms.TApplication.DialogHandle

// BeginCode
{
Here is replacement of the window procedure for Delphi's
encapsulation of the Windows search-and-replace common dialog
box. Click on Button2 to activate an open dialog and send
a WM_NCACTIVATE to FindReplaceWndProc.
}
function FindReplaceWndProc(Wnd: HWND; Msg, WParam, LParam: Longint): Longint; stdcall;

  function CallDefWndProc: Longint;
  begin
    Result := CallWindowProc(Pointer(GetProp(Wnd,
      MakeIntAtom(WndProcPtrAtom))), Wnd, Msg, WParam, LParam);
  end;

begin
  case Msg of
    WM_DESTROY:
      if Application.DialogHandle = Wnd then Application.DialogHandle := 0;
    WM_NCACTIVATE:
      if WParam <> 0 then
      begin
        if Application.DialogHandle = 0 then Application.DialogHandle := Wnd;
      end else
      begin
        if Application.DialogHandle = Wnd then Application.DialogHandle := 0;
      end;
    WM_NCDESTROY:
      begin
        Result := CallDefWndProc;
        RemoveProp(Wnd, MakeIntAtom(WndProcPtrAtom));
        Exit;
      end;
   end;
   Result := CallDefWndProc;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ReplaceDialog1.Execute;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  OpenDialog1.Execute;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  AtomText: array[0..31] of Char;
begin
  WndProcPtrAtom := GlobalAddAtom(StrFmt(AtomText,
    'WndProcPtr%.8X%.8X', [HInstance, GetCurrentThreadID]));
  SetWindowLong(Application.Handle, GWL_WNDPROC, Longint(@FindReplaceWndProc));;
end;
// EndCode
// EndExample: DialogHandle
end.
