わびさびサンプルソース

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

サービスの停止

サービスを停止するには、OpenService()関数にSERVICE_STOPを渡してオープンして、ControlService()関数をSERVICE_CONTROL_STOPを指定して呼び出します。

サービスの停止
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdio.h>
#include <tchar.h>
#include <locale.h>
#include <iostream>
#include <windows.h>
 
 
 
/*
    サービスの停止
*/
int StopService
(
    std::wstring strServiceName // サービス名
)
{
    // 処理結果
    int nRet = 0;
 
    // サービスデータベースハンドル
    SC_HANDLE hSvcDB = NULL;
 
    // サービスハンドル
    SC_HANDLE hService = NULL;
 
    // サービスステータス
    SERVICE_STATUS tServiceStatus;
 
 
    /*
        サービス制御マネージャのデータベースを開く
    */
    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_STOP );
    if ( NULL == hService ) {
 
        // エラー
        wprintf( L"OpenService err = 0x%08x", ::HRESULT_FROM_WIN32( ::GetLastError() ) );
        nRet = -1;
        goto err;
    }
 
    // サービスの一時停止
    if ( 0 == ::ControlService( hService, SERVICE_CONTROL_STOP, &tServiceStatus ) ) {
 
        // エラー
        wprintf( L"ControlService 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 != StopService( SERVICE_NAME ) ) {
 
        // エラー
        std::wcout << L"サービスの停止に失敗しました。" << std::endl;
        return( -1 );
    }
 
    // 処理結果を返す
    return( 0 );
}

実行結果

サービスを停止しました。






わびさびサンプルソース

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