实现一个程序在另一个程序内运行

来源:互联网 发布:知乎搞笑故事 编辑:程序博客网 时间:2024/05/21 18:39
 

首先制作一个子程序,这个程序用于在主程序中指定位置运行。

随便拖一个 exe 就行了,设置窗体的 Caption 为 Child。

然后制作主程序,在主窗体中放上一个Panel ,子程序将在这个 Panel 中运行。注意,不需要把主程序设为 MDIForm。

编写以下代码即可:

 

 

 

  1. unit frmMain;
  2. interface
  3. uses
  4.    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  5.    Dialogs, StdCtrls, ExtCtrls, ShellAPI, TlHelp32;
  6. type
  7.    TForm1 = class(TForm)
  8.      Panel1: TPanel;
  9.      Button1: TButton;
  10.      pnlChildForm: TPanel;
  11.      Timer1: TTimer;
  12.      procedure Button1Click(Sender: TObject);
  13.      procedure Timer1Timer(Sender: TObject);
  14.    private
  15.      { Private declarations }
  16.    public
  17.      { Public declarations }
  18.    end;
  19. var
  20.    Form1              : TForm1;
  21. implementation
  22. {$R *.dfm}
  23. function TaskExists(ExeFileName: string): Boolean;
  24. const
  25.    PROCESS_TERMINATE = $0001;
  26. var
  27.    ContinueLoop       : BOOL;
  28.    FSnapshotHandle    : THandle;
  29.    FProcessEntry32    : TProcessEntry32;
  30. begin
  31.    result := False;
  32.    FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  33.    FProcessEntry32.dwSize := Sizeof(FProcessEntry32);
  34.    ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
  35.    while integer(ContinueLoop) <> 0 do
  36.    begin
  37.      if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
  38.        UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) =
  39.        UpperCase(ExeFileName))) then
  40.      begin
  41.        Result := True;
  42.        Break;
  43.      end;
  44.      ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  45.    end;
  46. end;
  47. procedure TForm1.Button1Click(Sender: TObject);
  48. begin
  49.    if not TaskExists('ChildForm.exe'then
  50.      ShellExecute(0'open''ChildForm.exe',
  51.        nil, PChar(ExtractFilePath(ParamStr(0))), SW_SHOW);
  52. end;
  53. procedure TForm1.Timer1Timer(Sender: TObject);
  54. var
  55.    h                  : THandle;
  56. begin
  57.    if TaskExists('ChildForm.exe'then
  58.    begin
  59.      h := FindWindow(nil'Child');
  60.      windows.SetParent(h, pnlChildForm.Handle);
  61.    end;
  62. end;
  63. end.

运行程序后可以看到,子程序在主程序内运行,效果类似于 MDI 窗体

完整程序下载:

点击下载

原创粉丝点击