This article will explain how to add a user name to the Events that are logged in to the Event Viewer.
I needed to add user names to events that were being logged, and I could not find anything directly on target. Microsoft's website stated to simply add the SID to the
ReportEvent function. It did not tell how to get the SID. After much more investigation, I found something written in another programming language that got the user SID, so I translated it into C and combined it with what I was doing.
Using the code
I wrote a standalone program first to test out what I wanted to do at work. I will provide all the relevant portions here so that you can simply paste into your project something that works.
HANDLE g_eventHandle = NULL;
DWORD dwLength = 0;
PTOKEN_USER pTokenUser = NULL;
g_eventHandle = RegisterEventSource(NULL, _T("SID_TEST"));
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
pTokenUser = (PTOKEN_USER)HeapAlloc(GetProcessHeap(),
if (pTokenUser == NULL)
params = const_cast<TCHAR*>("test string");
rc = ReportEvent(g_eventHandle, EVENTLOG_INFORMATION_TYPE, 0, 0,
1, 0, (LPCTSTR *)params, NULL);
if (pTokenUser != NULL)
HeapFree(GetProcessHeap(), 0, (LPVOID)pTokenUser);
Points of Interest
That's all there is to it. The
GetTokenInformation function has to be called twice; if you have too much or too little allocated for your SID, the function will fail.
The Event View with our entry: