如何写代码启动/停止一个Windows服务?(200分)

  • 主题发起人 主题发起人 dawnsoft
  • 开始时间 开始时间
D

dawnsoft

Unregistered / Unconfirmed
GUEST, unregistred user!
如何写代码启动/停止一个指定名称的Windows服务?最好能够提供相关的代码。多谢。
 
net start 服务名称<br>net stop 服务名称
 
procedure TForm1.Button1Click(Sender: TObject);<br>begin<br> &nbsp;WinExec('net start mysql',SW_SHOW);//启动mysql服务<br>end;
 
自己搞掂。。<br>function StartService(AServName: string): Boolean; //use WinSvc<br>var<br> &nbsp;SCManager, hService: SC_HANDLE;<br> &nbsp;lpServiceArgVectors: PChar;<br>begin<br> &nbsp;SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);<br> &nbsp;Result := SCManager &lt;&gt; 0;<br> &nbsp;if Result then<br> &nbsp;try<br> &nbsp; &nbsp;hService := OpenService(SCManager, PChar(AServName), SERVICE_ALL_ACCESS);<br> &nbsp; &nbsp;Result := hService &lt;&gt; 0;<br> &nbsp; &nbsp;if (hService = 0) and (GetLastError = ERROR_SERVICE_DOES_NOT_EXIST) then<br> &nbsp; &nbsp; &nbsp;Exception.Create('The specified service does not exist');<br> &nbsp; &nbsp;if hService &lt;&gt; 0 then<br> &nbsp; &nbsp;try<br> &nbsp; &nbsp; &nbsp;lpServiceArgVectors := nil;<br> &nbsp; &nbsp; &nbsp;Result := WinSvc.StartService(hService, 0, PChar(lpServiceArgVectors));<br> &nbsp; &nbsp; &nbsp;if not Result and (GetLastError = ERROR_SERVICE_ALREADY_RUNNING) then<br> &nbsp; &nbsp; &nbsp; &nbsp;Result := True;<br> &nbsp; &nbsp;finally<br> &nbsp; &nbsp; &nbsp;CloseServiceHandle(hService);<br> &nbsp; &nbsp;end;<br> &nbsp;finally<br> &nbsp; &nbsp;CloseServiceHandle(SCManager);<br> &nbsp;end;<br>end;<br><br><br>function StopService(AServName: string): Boolean;<br>var<br> &nbsp;SCManager, hService: SC_HANDLE;<br> &nbsp;SvcStatus: TServiceStatus;<br>begin<br> &nbsp;SCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);<br> &nbsp;Result := SCManager &lt;&gt; 0;<br> &nbsp;if Result then<br> &nbsp;try<br> &nbsp; &nbsp;hService := OpenService(SCManager, PChar(AServName), SERVICE_ALL_ACCESS);<br> &nbsp; &nbsp;Result := hService &lt;&gt; 0;<br> &nbsp; &nbsp;if Result then<br> &nbsp; &nbsp;try &nbsp;//停止并卸载服务;<br> &nbsp; &nbsp; &nbsp;Result := ControlService(hService, SERVICE_CONTROL_STOP, SvcStatus);<br> &nbsp; &nbsp; &nbsp;//删除服务,这一句可以不要;<br>// &nbsp; &nbsp; &nbsp;DeleteService(hService);<br> &nbsp; &nbsp;finally<br> &nbsp; &nbsp; &nbsp;CloseServiceHandle(hService);<br> &nbsp; &nbsp;end;<br> &nbsp;finally<br> &nbsp; &nbsp;CloseServiceHandle(SCManager);<br> &nbsp;end;<br>end;
 
同意楼上的。
 
同意楼上,net系列命令
 
倒 来迟了。 net 命令能添加帐号 查看共享。。。。。很多与网络应用有关的 都能用net命令, 知道是什么命令 直接放shell里执行就ok了
 
StartService太简单了 还没有加上IP 启动参数等等 很难的问题 表面看没有问题 实战使用就知道
 
多人接受答案了。
 
后退
顶部