如何判断一个程序在运行当中:
我在主程序中启动了一个辅助的程序,
我想当我的主程序关闭之后辅程序也关闭。
请问怎么办?

解决方案 »

  1.   

    如果只是简单方法:
    下面给出一段在 Delphi 中关闭“计算器”程序为例:
    ...
    var
      HWndCalculator : HWnd;
    begin
       // find the exist calculator window
      HWndCalculator := Winprocs.FindWindow(nil, '计算器');   // close the exist Calculator }
      if HWndCalculator <> 0 then  
         SendMessage(HWndCalculator, WM_CLOSE, 0, 0);
    end;下面是复杂的调用var
       pWindowsList: pointer;
       hActiveWindow: HWnd;
       hExeHandle: THandle;
    begin
       pWindowsList := DisableTaskWindows(0);
       hActiveWindow := GetActiveWindow;
       try
          hExeHandle := WinExec('arj.exe /?',SW_SHOWNORMAL);
          while GetModuleUsage(hExeHandle) <> 0 do
          Application.ProcessMessages;
       finally
          EnableTaskWindows(pWindowsList);
          SetActiveWindow(hActiveWindow);
       end;
    end;
    // 相信你明白了。
    题外话:如果执行的是 MSDOS 外部程序,如何能让它的窗口不显示出来呢? [ 接上例 ]:
    TStartupInfo 这个结构中有一个 sShowWindow 栏位, 将之设为 SW_HIDE即可,
    同时, dwFlags 标志中至少需含有 STARTF_USESHOWWINDOW, 否则CreateProcess
    时, sShowWindow 栏位的设定会无效, 以下是修改过的程式:var
       sCommandLine: string;
       bCreateProcess: boolean;
       lpStartupInfo: TStartupInfo;
       lpProcessInformation: TProcessInformation;
    begin
       // sCommandLine 的内容请视您的情况修改
       sCommandLine :='Xcopy d:\temp\temp1\*.* d:\temp\temp2 /v/y';
       lpStartupInfo.dwFlags := STARTF_USESHOWWINDOW;
       lpStartupInfo.wShowWindow := SW_HIDE;
       bCreateProcess := CreateProcess(nil, PChar(sCommandLine),nil,nil,True,
                    HIGH_PRIORITY_CLASS, nil, nil,lpStartupInfo, lpProcessInformation);
       if bCreateProcess then
            WaitForSingleObject(lpProcessInformation.hProcess, INFINITE);
    end;
    // 又有进步了