我建立了一个Service Application,中间有一个Thread,在一定条件下,我需要它运行另一个外部的程序。
可以当我启动服务,外部程序并没有显示的运行,在任务管理器中可以看到,而且不能够终止。请问这是为什么,要怎样才能够解决。代码大概是这样子的:unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs;type
  T = class(TThread)
  protected
    procedure Execute; override;  end;
  TService1 = class(TService)
    procedure ServiceStart(Sender: TService; var Started: Boolean);
  private
    { Private declarations }
    tt: T;
  public
    function GetServiceController: TServiceController; override;
    { Public declarations }
  end;var
  Service1: TService1;implementation{$R *.DFM}procedure ServiceController(CtrlCode: DWord); stdcall;
begin
  Service1.Controller(CtrlCode);
end;function TService1.GetServiceController: TServiceController;
begin
  Result := ServiceController;
end;procedure T.Execute;
begin
  while true do
  begin
    if fileexists('c:\start.txt') then //某一个条件满足
      winexec('notepad.exe', SW_SHOWNORMAL); //运行一个程序,但看不到窗口
    sleep(1000);
  end;
end;
                                            
procedure TService1.ServiceStart(Sender: TService; var Started: Boolean);
begin
  tt := T.Create(false);
  Started := True;
end;end.

解决方案 »

  1.   

    PS:
    OS: windows 2000 prof
    IDE: Delphi 6
      

  2.   

    将winexec('notepad.exe', SW_SHOWNORMAL);改为 ShellExecuteEx试一试
      

  3.   

    我试了CreateProcess & ShellExecute,都不行
    不知道是不是我用错了:ShellExecute(0, nil, 'notepad.exe', nil, nil, SW_SHOWNORMAL);
    or
    ShellExecute(0, nil, 'c:\start.txt', nil, nil, SW_SHOWNORMAL);ShellExecuteEx,还不会用,请问能给一个具体的解决方案吗?
    谢谢。
      

  4.   

    http://expert.csdn.net/Expert/topic/1342/1342008.xml?temp=.6818506
      

  5.   

    >>就是等到外部程序执行完了,我的程序再继续执行对于这个问题,我觉得用WaitForSingleObject,
    把TIME_OUT设为MAXINT就可以了。
    我不大明白 wks(mex) 的意思,
    你是说用你文中的CreateProcess参数就可以解决这个问题吗?
      

  6.   

    我遇到过同样的问题,可是你的具体问题是怎样我也不清楚,给你提供几个调试的方法:
    1、首先查看你的操作系统是不是Windows2000以上,因为Win9x不支持服务
    2、WinExec是16位Api,在32系统中,最好不用它,而用CreateProcess或ShellExecute
    3、检查你是否成功安装了服务,在控制面板-〉管理工具-〉服务中有没有你的服务(你的服务名是否存在列表中)
    3、那些Api函数都有返回值,看看运行的返回值是多少。因为服务不好调试,你最好将返回值写入文件。运行后看返回值是多少,对比SDK帮助找是什么问题你先按照上面的检查和调试一下,如果还不能解决,咱们再探讨
      

  7.   

    我没在线程中用过CreateProcess,不过你可以试一试,函数是现成的,你调用一下看行不行
      

  8.   

    to aliceZOOZ(alice):
    //>>就是等到外部程序执行完了,我的程序再继续执行
    //对于这个问题,我觉得用WaitForSingleObject,
    //把TIME_OUT设为MAXINT就可以了。
    这种不行就换一种,没有必要在一棵树上吊死,别管高树矮树,能吊死的就是好树
      

  9.   

    先uses ShellApi;ShellExecute(Handle, 'Open', '完整路径', nil, nil, SW_SHOW);
      

  10.   

    我发现在Server里调用的Process是System用户,所以我用CreateProcessAsUser,切换到当前用户,但还是没有窗口显示。在CreateProcessAsUser中,有一个lpDesktop参数,若不指定,则继承父进程的lpDesktop,而父进程是以System登陆的。我想问题应该就出在这里。但如何才能得到当前正在使用的用户的lpDesktop呢?