Include header file: # include <winsvc. h>
The following uses Web services as an example:
# Include <winsvc. h>
Void cstartservicedlg: onbnclickedbutton1 ()
...{
// Open the service management object
SC _handle HSCC =: openscmanager (null,
Null, generic_execute );
If (SCS = NULL)
...{
Trace ("Open scmanager error ");
Return;
}
// Open the WWW Service.
SC _handle HSVC =: openservice (SCS, "W3SVC ",
Service_start | service_query_status | service_stop );
If (HSVC = NULL)
...{
Trace ("Open WWW erron. ");
: Closeservicehandle (SCS );
Return;
}
// Obtain the service status
Service_status status;
If (: queryservicestatus (HSVC, & Status) = false)
...{
Trace ("Get service state error. ");
: Closeservicehandle (HSVC );
: Closeservicehandle (SCS );
Return;
}
// If it is in the stopped status, start the service; otherwise, stop the service.
If (status. dwcurrentstate = service_running)
...{
// Stop the service
If (: controlservice (HSVC,
Service_control_stop, & Status) = false)
...{
Trace ("Stop Service error. ");
: Closeservicehandle (HSVC );
: Closeservicehandle (SCS );
Return;
}
// Wait for the service to stop
While (: queryservicestatus (HSVC, & Status) = true)
...{
: Sleep (status. dwwaithint );
If (status. dwcurrentstate = service_stopped)
...{
Afxmessagebox ("Stop success. ");
: Closeservicehandle (HSVC );
: Closeservicehandle (SCS );
Return;
}
}
}
Else if (status. dwcurrentstate = service_stopped)
...{
// Start the service
If (: startservice (HSVC, null, null) = false)
...{
Trace ("Start service error. ");
: Closeservicehandle (HSVC );
: Closeservicehandle (SCS );
Return;
}
// Wait for the service to start
While (: queryservicestatus (HSVC, & Status) = true)
...{
: Sleep (status. dwwaithint );
If (status. dwcurrentstate = service_running)
...{
Afxmessagebox ("START success. ");
: Closeservicehandle (HSVC );
: Closeservicehandle (SCS );
Return;
}
}
}
Trace ("START error. ");
: Closeservicehandle (HSVC );
: Closeservicehandle (SCS );
Return;
}