サービスを開始するには、OpenService()関数にSERVICE_STARTを渡してオープンして、StartService()関数を呼び出します。
#include <stdio.h>
#include <tchar.h>
#include <locale.h>
#include <iostream>
#include <windows.h>
/*
サービスの開始
*/
int StartService
(
std::wstring strServiceName // サービス名
)
{
// 処理結果
int nRet = 0;
// サービスデータベースハンドル
SC_HANDLE hSvcDB = NULL;
// サービスハンドル
SC_HANDLE hService = NULL;
/*
サービス制御マネージャのデータベースを開く
*/
hSvcDB = ::OpenSCManager( NULL, NULL, SC_MANAGER_CONNECT );
if ( NULL ) {
// エラー
wprintf( L"OpenSCManager err = 0x%08x", ::HRESULT_FROM_WIN32( ::GetLastError() ) );
nRet = -1;
goto err;
}
// サービスのオープン
hService = ::OpenService( hSvcDB, strServiceName.c_str(), SERVICE_START );
if ( NULL == hService ) {
// エラー
wprintf( L"OpenService err = 0x%08x", ::HRESULT_FROM_WIN32( ::GetLastError() ) );
nRet = -1;
goto err;
}
// サービスの開始
if ( 0 == ::StartService( hService, 0, NULL ) ) {
// エラー
wprintf( L"StartService err = 0x%08x", ::HRESULT_FROM_WIN32( ::GetLastError() ) );
nRet = -1;
goto err;
}
// サービス開始成功
std::wcout << L"サービスを開始しました。" << std::endl;
err:
// サービスクローズ
if ( NULL != hService ) {
::CloseServiceHandle( hService );
}
// データベースクローズ
if ( NULL != hSvcDB ) {
::CloseServiceHandle( hSvcDB );
}
// 処理結果
return( nRet );
}
// サービス名称
#define SERVICE_NAME L"TestService"
/*
サービスの開始
*/
int _tmain
(
int argc
, _TCHAR* argv[]
)
{
// std::wcoutのロケールを設定
std::wcout.imbue( std::locale( "", std::locale::ctype ) );
// サービスの開始
if ( 0 != StartService( SERVICE_NAME ) ) {
// エラー
std::wcout << L"サービスの開始に失敗しました。" << std::endl;
return( -1 );
}
// 処理結果を返す
return( 0 );
}
サービスを開始しました。