How to enable and stop windows Services with delphi

Source: Internet
Author: User

Function StartService (AServName: string): Boolean; // use WinSvc
Var
SCManager, hService: SC _HANDLE;
LpServiceArgVectors: PChar;
Begin
SCManager: = OpenSCManager (nil, nil, SC _MANAGER_ALL_ACCESS );
Result: = SCManager <> 0;
If Result then
Try
HService: = OpenService (SCManager, PChar (AServName), SERVICE_ALL_ACCESS );
Result: = hService <> 0;
If (hService = 0) and (GetLastError = ERROR_SERVICE_DOES_NOT_EXIST) then
Exception. Create ('the specified service does not exist ');
If hService <> 0 then
Try
LpServiceArgVectors: = nil;
Result: = WinSvc. StartService (hService, 0, PChar (lpServiceArgVectors ));
If not Result and (GetLastError = ERROR_SERVICE_ALREADY_RUNNING) then
Result: = True;
Finally
CloseServiceHandle (hService );
End;
Finally
CloseServiceHandle (SCManager );
End;
End;

// If you want to publish this article, please indicate the exit, no outgoing copyright notice, I do not like to see this kind of website. My work website does not indicate the person who is serving Seven {See7di # Gmail.com}
Function StopService (AServName: string): Boolean;
Var
SCManager, hService: SC _HANDLE;
SvcStatus: TServiceStatus;
Begin
SCManager: = OpenSCManager (nil, nil, SC _MANAGER_ALL_ACCESS );
Result: = SCManager <> 0;
If Result then
Try
HService: = OpenService (SCManager, PChar (AServName), SERVICE_ALL_ACCESS );
Result: = hService <> 0;
If Result then
Try // stop and uninstall the service;
Result: = ControlService (hService, SERVICE_CONTROL_STOP, SvcStatus );
// Delete the service. This sentence is optional;
// DeleteService (hService );
Finally
CloseServiceHandle (hService );
End;
Finally
CloseServiceHandle (SCManager );
End;
End;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.