1

Windows サービスをインストールして開始する単純な C++ WIN32 API プログラムを作成しています。コードで SEH __try&__finaly を使用しています。残念ながら、次のような既知のエラーが発生します。

error C2712 Cannot use __try in functions that require object unwinding.

SEHコードをメイン関数から別の関数に移動したり、プロジェクトのプロパティでエラーを再生したりするなど、おなじみの方法で解決しようとしました:C++例外を有効にします。しかし、何も機能しませんでした。とにかく、これはソースです:

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;

#define ERROR -1
#define SUCCESS 0;

string GetLastErrorAsString(DWORD errorMessageID);
DWORD Service();
int WINAPI main(void)
{
    wcout << "STARTING THE SERVICE INSTALLATION PROCESS..." << endl;
    Service();
    wcout << "FINISHED !" << endl;
    wcout << "ENTER ANYTHING TO EXIT..." << endl;
    getchar();
    return 0;
}

**DWORD Service() {** << the line that the error is pointing at
    SC_HANDLE hSCManager = NULL;
    SC_HANDLE hService = NULL;
    DWORD start_service = 0;
    LPCTSTR ExePath = TEXT("C:\Program Files\WinSecurityCheck.exe");
    __try { //guarded code here 

        hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
        if (hSCManager == NULL) {
            __leave;
        }
        hService = CreateService(hSCManager, TEXT("WinSecurityCheck"),
        TEXT("WinSeurityCheck"),
        SERVICE_START | DELETE | SERVICE_STOP,
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_AUTO_START,
        SERVICE_ERROR_IGNORE,
        ExePath, NULL, NULL, NULL, NULL, NULL);
        if (hService == NULL) {
            __leave;
        }
        start_service = StartService(hService, 0, NULL);
        if (start_service == 0) {
            __leave;
        }
    }
    __finally { //termination code
        if (!AbnormalTermination()) {
            wcout << TEXT("Successfully Created & Started The Desired     Service") << endl;
            CloseServiceHandle(hSCManager);
            CloseServiceHandle(hService);
            return SUCCESS;
        }
        if (hSCManager == NULL) {

            wcout << TEXT("Error Open SC Manager") << endl;
            GetLastErrorAsString(GetLastError());
            return ERROR;
        }
        if (hService)
        {
            wcout << TEXT("Error Creating Service") << endl;
            GetLastErrorAsString(GetLastError());

            CloseServiceHandle(hSCManager);
            return ERROR;
        }
        if (start_service == 0)
        {
            wcout << TEXT("Error Starting Service") << endl;
            GetLastErrorAsString(GetLastError());
            CloseServiceHandle(hService);
            CloseServiceHandle(hSCManager);
            return ERROR;
        }
    }
}

string GetLastErrorAsString(DWORD errorMessageID) {
    LPTSTR formatMessage;
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS     | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, errorMessageID, NULL, formatMessage, 64,       NULL);
    wcout << formatMessage << endl;
    LocalFree(formatMessage);
}
4

0 に答える 0