我想在一个程序中调用另一个程序,代码如下:
procedure TForm1.Button1Click(Sender: TObject);
var
  ExePath: string;
begin
  ExePath := 'D:\HKComplain.exe';
  if FileExists(ExePath) then
    ShellExecute(HANDLE, 'OPEN', PChar(ExePath), '', '', SW_SHOWNORMAL)
  else
    ShowMessage('系统无法找到该文件!');    
end;
但有一个问题:在主程序中执行这个程序后,如果主程序关闭,则调用的程序仍然在执行。而在Delphi的IDE中,我们调用DataDesktop等程序时,当Delphi关闭, Data Desktop程序也关闭了。请问这种调用方式下,调用的代码有何不同?该如何实现呢?

解决方案 »

  1.   

    在主窗体close的时候,给'D:\HKComplain.exe'发WM_CLOSE
      

  2.   

    ShellExecute(0, PChar(ExePath), nil, nil, nil, SW_SHOWNORMAL)就可以达到这样的效果。
      

  3.   

    写错了,应为ShellExecute(0, nil, PChar(ExePath), nil, nil, SW_SHOWNORMAL)
      

  4.   

    along3000(飞龙) 你這樣是可行,不過有個問題喲!!!
    比如我已經在打開另一個程序時,自己把它給關閉啦,那就可以不用啦
    所以我現在有個問題.
    我一個程序中可以調用好多個子程序,我想在我關閉主程序時,怎麼來判斷我自己打開的子
    程序但還未關閉的,同時這些子程序有可能不是通過這個主程序打開的,它有可能是自己打開的.
    希望多多指教.
      

  5.   

    不要用ShellExecute -- 功能太弱 ;请用CreateProcess() ,用CreateProcess可以获取到被创建进程的进程ID等信息,将这些信息用一链表保存起来,你在主进程退出时,关闭你自己创建的进程就行了撒。
      

  6.   

    用CreateProcess创建进程,用TerminateProcess来关闭进程unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls;type
      TForm1 = class(TForm)
        Button1: TButton;
        Button2: TButton;
        procedure FormCanResize(Sender: TObject; var NewWidth,
          NewHeight: Integer; var Resize: Boolean);
        procedure Button1Click(Sender: TObject);
        procedure Button2Click(Sender: TObject);
      private
        { Private declarations }
      public
        { Public declarations }
      end;var
      Form1: TForm1;implementation{$R *.dfm}
    var
      lpProcessInformation: TProcessInformation;procedure TForm1.FormCanResize(Sender: TObject; var NewWidth,
      NewHeight: Integer; var Resize: Boolean);
    begin
     with button1 do
      begin
        //top:=round(form1.height/5);//也可以为NewHeight,NewWidth
        width:=round(form1.width/5);
        //left:=round(form1.width/7);
        height:=round(form1.height/7);
      end;
    end;procedure TForm1.Button1Click(Sender: TObject);
    var
      sCommandLine: string;
      bCreateProcess: boolean;
      lpStartupInfo: TStartupInfo;
    begin
      sCommandLine := 'E:\Demo\Demo.exe';
      FillChar(lpStartupInfo, Sizeof(TStartupInfo), #0);
      lpStartupInfo.cb := Sizeof(TStartupInfo);  bCreateProcess := CreateProcess(nil, PChar(sCommandLine),
        nil, nil, True, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS,
        nil, nil, lpStartupInfo, lpProcessInformation);
    end;procedure TForm1.Button2Click(Sender: TObject);
    begin
       TerminateProcess(lpProcessInformation.hProcess,PROCESS_TERMINATE);
    end;end.
      

  7.   

    获得你创建进程的句柄
    在退出时关闭那个进程
    参见tlhelp32的说明