Skip to content

Commit

Permalink
Use GetUserNameExW to query user name on windows
Browse files Browse the repository at this point in the history
  • Loading branch information
tehKaiN committed Aug 27, 2022
1 parent 16c51cf commit 5da8548
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
2 changes: 1 addition & 1 deletion libs/common/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ IF (WIN32)
target_compile_definitions(s25util_common PRIVATE WIN32_LEAN_AND_MEAN _WIN32_WINNT=0x0600) # Win Vista
# Exclude some windows defines
target_compile_definitions(s25util_common PRIVATE NOMINMAX NODRAWTEXT NOSOUND NOTEXTMETRIC NOCOMM NOMCX)
target_link_libraries(s25util_common PUBLIC Boost::locale Boost::disable_autolinking iphlpapi)
target_link_libraries(s25util_common PUBLIC Boost::locale Boost::disable_autolinking iphlpapi secur32)
ENDIF ()

include(EnableWarnings)
Expand Down
10 changes: 7 additions & 3 deletions libs/common/src/System_Win32.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
#include <boost/nowide/convert.hpp>
#include <windows.h>
#include <shellapi.h>
#ifndef SECURITY_WIN32
# define SECURITY_WIN32
#endif
#include <security.h>
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4091) // "typedef ": Ignoriert auf der linken Seite von "tagGPFIDL_FLAGS"
Expand Down Expand Up @@ -112,14 +116,14 @@ std::string System::getUserName()
{
DWORD nameLen = 0;
// Query required size
GetUserNameW(nullptr, &nameLen);
GetUserNameExW(EXTENDED_NAME_FORMAT::NameDisplay, nullptr, &nameLen); // nameLen contains terminating 0 here
if(nameLen == 0)
throw std::runtime_error("Could not query username length");
std::vector<wchar_t> userName(nameLen);
if(GetUserNameW(userName.data(), &nameLen) == 0)
if(GetUserNameExW(EXTENDED_NAME_FORMAT::NameDisplay, userName.data(), &nameLen) == 0)
throw std::runtime_error("Could not get username");

userName.resize(nameLen - 1); // nameLen already contains terminating 0
userName.resize(nameLen); // nameLen doesn't contain terminating 0 here

return boost::nowide::narrow(std::wstring(userName.begin(), userName.end()));
}

0 comments on commit 5da8548

Please sign in to comment.