Windows 事件日誌

程式碼


#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

class EventLog {
private:
	WORD logCategory = 0;
	DWORD logId = 0;
	HANDLE hEventLog = 0;
public:
	EventLog();
	~EventLog();

	BOOL OpenLog(LPCSTR logSource);
	VOID CloseLog();
	BOOL Log(LPCSTR* arrMessages, size_t numOfMessages);
};

EventLog::EventLog() 
{
	srand((unsigned) time(NULL));
}
EventLog::~EventLog() 
{
}

BOOL EventLog::OpenLog(LPCSTR logSource) {
	this->hEventLog = RegisterEventSource(NULL, logSource);
	return (this->hEventLog != 0);
}

VOID EventLog::CloseLog() {
	if (this->hEventLog) {
		DeregisterEventSource(this->hEventLog);
		this->hEventLog = 0;
	}
}

BOOL EventLog::Log(LPCSTR* arrMessages, size_t numOfMessages)
{
	BOOL OK = FALSE;

	if (this->hEventLog) 
	{
		this->logCategory = (WORD) rand();
		this->logId = (DWORD) rand();

		if (ReportEvent(hEventLog,	        // Event log handle
			EVENTLOG_INFORMATION_TYPE,      // Event type
			this->logCategory,              // Event category
			this->logId,			// Event identifier
			NULL,				// No security identifier
			(WORD) numOfMessages,		// Size of messages array
			0,				// No binary data
			arrMessages,			// Array of messages
			NULL				// No binary data
		))
		{
			OK = TRUE;
		}
	}

	return OK;
}

int main() {
	LPCSTR arrMessages[] = { "訊息 1", "訊息 2", "訊息 3" };
	EventLog *eventLog = new EventLog();

	if (eventLog->OpenLog("張三豐"))
	{
		eventLog->Log(arrMessages, 3);
		eventLog->CloseLog();

		printf("OK");
	}

	delete eventLog;

	return 0;
}

管理畫面