わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

サービスの削除

サービスを削除するには、OpenService()関数にDELETEを渡してオープンして、DeleteService()関数を呼び出します。

#include <stdio.h>
#include <tchar.h>
#include <locale.h>
#include <iostream>
#include <windows.h>



/*
	サービスの削除
*/
int DeleteService
(
	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(), DELETE );
	if ( NULL == hService ) {

		// エラー
		wprintf( L"OpenService err = 0x%08x", ::HRESULT_FROM_WIN32( ::GetLastError() ) );
		nRet = -1;
		goto err;
	}

    // サービスの削除
	if ( 0 == ::DeleteService( hService ) ) {

		// エラー
		wprintf( L"DeleteService 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"TestService2"



/*
	サービスの削除
*/
int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	// std::wcoutのロケールを設定
	std::wcout.imbue( std::locale( "", std::locale::ctype ) );

	// サービスの削除
	if ( 0 != DeleteService( SERVICE_NAME ) ) {

		// エラー
		std::wcout << L"サービスの削除に失敗しました。" << std::endl;
		return( -1 );
	}

	// 処理結果を返す
	return( 0 );
}



実行結果

サービスを削除しました。






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。