bCreateProcess := CreateProcess(nil, PChar(sCommandLine),nil, nil, True, CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS,nil, nil, lpStartupInfo, lpProcessInformation);                //创建线程   if bCreateProcess then
      WaitForSingleObject(lpProcessInformation.hProcess,INFINITE);//延时
    
    ......
目的:用以上代码控制打开Word文档后,产生延时,直至Word文档关闭,再继续执行后面的程序。
问题:
当系统没有Word文件打开时,程序执行正确。
但程序执行前如果有一个Word文档已经打开,则没有了延时效果,直接执行后面的程序。
请问为什么会这样?有什么解决的方法?

解决方案 »

  1.   

    function RunExeFile(const Prog, CommandLine, Dir: string; var ExitCode: DWORD):
      string;  procedure CheckResult(b: Boolean);
      begin
        if not b then
          raise Exception.Create(SysErrorMessage(GetLastError));
      end;
    var
      HRead, HWrite     : THandle;
      StartInfo         : TStartupInfo;
      ProceInfo         : TProcessInformation;
      b                 : Boolean;
      sa                : TSecurityAttributes;
    begin
      Result := '';
      FillChar(sa, sizeof(sa), 0);
      //设置允许继承,否则在NT和2000下无法取得输出结果
      sa.nLength := sizeof(sa);
      sa.bInheritHandle := True;
      sa.lpSecurityDescriptor := nil;
      b := CreatePipe(HRead, HWrite, @sa, 0);
      CheckResult(b);  FillChar(StartInfo, SizeOf(StartInfo), 0);
      StartInfo.cb := SizeOf(StartInfo);
      StartInfo.wShowWindow := SW_SHOW;
      //使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式
      StartInfo.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW;
      StartInfo.hStdError := HWrite;
      StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); //HRead;
      StartInfo.hStdOutput := HWrite;  b := CreateProcess(PChar(Prog),       //lpApplicationName: PChar
        PChar(CommandLine),                 //lpCommandLine: PChar
        nil, //lpProcessAttributes: PSecurityAttributes
        nil,                                //lpThreadAttributes: PSecurityAttributes
        True,                               //bInheritHandles: BOOL
        CREATE_NEW_CONSOLE,
        nil,
        PChar(Dir),
        StartInfo,
        ProceInfo);  CheckResult(b);
      WaitForSingleObject(ProceInfo.hProcess, INFINITE);
      GetExitCodeProcess(ProceInfo.hProcess, ExitCode);
    end;可以尝试使用该段代码,本人使用得;以下是调用:
        try
          RunExeFile(ExecName, ExecName,
            ExtractFileDir(ExecName),
            exitCode);
        finally
          DeleteFile(ExecName);
          FormMain.WindowState := wsNormal;
          if exitCode <> 0 then
          begin
            application.MessageBox(PAnsiChar(format('返回状态码: %d', [exitCode])),
              '执行文件结果', mb_ok or mb_IconInformation);
          end;
        end;