首先制作一个子程序,这个程序用于在主程序中指定位置运行。
随便拖一个 exe 就行了,设置窗体的 Caption 为 Child。
然后制作主程序,在主窗体中放上一个Panel ,子程序将在这个 Panel 中运行。注意,不需要把主程序设为 MDIForm。
编写以下代码即可:
- unit frmMain;
- interface
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, StdCtrls, ExtCtrls, ShellAPI, TlHelp32;
- type
- TForm1 = class(TForm)
- Panel1: TPanel;
- Button1: TButton;
- pnlChildForm: TPanel;
- Timer1: TTimer;
- procedure Button1Click(Sender: TObject);
- procedure Timer1Timer(Sender: TObject);
- private
- { Private declarations }
- public
- { Public declarations }
- end;
- var
- Form1 : TForm1;
- implementation
- {$R *.dfm}
- function TaskExists(ExeFileName: string): Boolean;
- const
- PROCESS_TERMINATE = $0001;
- var
- ContinueLoop : BOOL;
- FSnapshotHandle : THandle;
- FProcessEntry32 : TProcessEntry32;
- begin
- result := False;
- FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
- FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
- ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
- while integer(ContinueLoop) <> 0 do
- begin
- if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
- UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) =
- UpperCase(ExeFileName))) then
- begin
- Result := True;
- Break;
- end;
- ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
- end;
- end;
- procedure TForm1.Button1Click(Sender: TObject);
- begin
- if not TaskExists('ChildForm.exe') then
- ShellExecute(0, 'open', 'ChildForm.exe',
- nil, PChar(ExtractFilePath(ParamStr(0))), SW_SHOW);
- end;
- procedure TForm1.Timer1Timer(Sender: TObject);
- var
- h : THandle;
- begin
- if TaskExists('ChildForm.exe') then
- begin
- h := FindWindow(nil, 'Child');
- windows.SetParent(h, pnlChildForm.Handle);
- end;
- end;
- end.
运行程序后可以看到,子程序在主程序内运行,效果类似于 MDI 窗体
完整程序下载: