1

我正在编写一个简单的 C++ WIN32 API 程序来安装和启动 Windows 服务。我在我的代码中使用 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