c++ - 无法获取和显示用户名的C++ Microsoft示例

标签 c++ windows winapi wchar-t tchar

我想以最简单的方式获取C++中的用户名。我的程序仅适用于Windows。

我想使用Microsoft example。我将代码示例复制粘贴到新的Visual Studio 2019中,但是TEXT指令出现错误:

a value of type "const wchar_t *" cannot be used to initialize an entity of type "TCHAR *"


TCHAR* envVarStrings[] =
{
  TEXT("OS         = %OS%"),
  TEXT("PATH       = %PATH%"),
  TEXT("HOMEPATH   = %HOMEPATH%"),
  TEXT("TEMP       = %TEMP%")
};
...
printError(TEXT("GetUserName"));
...

这是完整的代码:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>

TCHAR* envVarStrings[] =
{
  TEXT("OS         = %OS%"),
  TEXT("PATH       = %PATH%"),
  TEXT("HOMEPATH   = %HOMEPATH%"),
  TEXT("TEMP       = %TEMP%")
};
#define  ENV_VAR_STRING_COUNT  (sizeof(envVarStrings)/sizeof(TCHAR*))
#define INFO_BUFFER_SIZE 32767
void printError( TCHAR* msg );

void main( )
{
  DWORD i;
  TCHAR  infoBuf[INFO_BUFFER_SIZE];
  DWORD  bufCharCount = INFO_BUFFER_SIZE;

  // Get and display the name of the computer. 
  bufCharCount = INFO_BUFFER_SIZE;
  if( !GetComputerName( infoBuf, &bufCharCount ) )
    printError( TEXT("GetComputerName") ); 
  _tprintf( TEXT("\nComputer name:      %s"), infoBuf ); 

  // Get and display the user name. 
  bufCharCount = INFO_BUFFER_SIZE;
  if( !GetUserName( infoBuf, &bufCharCount ) )
    printError( TEXT("GetUserName") ); 
  _tprintf( TEXT("\nUser name:          %s"), infoBuf ); 

  // Get and display the system directory. 
  if( !GetSystemDirectory( infoBuf, INFO_BUFFER_SIZE ) )
    printError( TEXT("GetSystemDirectory") ); 
  _tprintf( TEXT("\nSystem Directory:   %s"), infoBuf ); 

  // Get and display the Windows directory. 
  if( !GetWindowsDirectory( infoBuf, INFO_BUFFER_SIZE ) )
    printError( TEXT("GetWindowsDirectory") ); 
  _tprintf( TEXT("\nWindows Directory:  %s"), infoBuf ); 

  // Expand and display a few environment variables. 
  _tprintf( TEXT("\n\nSmall selection of Environment Variables:") ); 
  for( i = 0; i < ENV_VAR_STRING_COUNT; ++i )
  {
    bufCharCount = ExpandEnvironmentStrings(envVarStrings[i], infoBuf,
        INFO_BUFFER_SIZE ); 
    if( bufCharCount > INFO_BUFFER_SIZE )
      _tprintf( TEXT("\n\t(Buffer too small to expand: \"%s\")"), 
              envVarStrings[i] );
    else if( !bufCharCount )
      printError( TEXT("ExpandEnvironmentStrings") );
    else
      _tprintf( TEXT("\n   %s"), infoBuf );
  }
  _tprintf( TEXT("\n\n"));
}

void printError( TCHAR* msg )
{
  DWORD eNum;
  TCHAR sysMsg[256];
  TCHAR* p;

  eNum = GetLastError( );
  FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | 
         FORMAT_MESSAGE_IGNORE_INSERTS,
         NULL, eNum,
         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
         sysMsg, 256, NULL );

  // Trim the end of the line and terminate it with a null
  p = sysMsg;
  while( ( *p > 31 ) || ( *p == 9 ) )
    ++p;
  do { *p-- = 0; } while( ( p >= sysMsg ) &&
                          ( ( *p == '.' ) || ( *p < 33 ) ) );

  // Display the message
  _tprintf( TEXT("\n\t%s failed with error %d (%s)"), msg, eNum, sysMsg );
}

如何制作函数,应包含哪些标题?
std::wstring getUsername() {
   //...
}

最佳答案

Win32 API提供您所需要的。函数GetUserNameWGetComputerNameW正是您所需要的,用法非常简单。这是一个有效的示例:

#include <iostream>
#include <string>
#include <windows.h>
#include <Lmcons.h>

std::wstring getUsername() {
    wchar_t username[UNLEN + 1];
    DWORD username_len = UNLEN + 1;
    GetUserNameW(username, &username_len);
    return username;
}

std::wstring getComputerName() {
    wchar_t computerName[UNLEN + 1];
    DWORD computerName_len = UNLEN + 1;
    GetComputerNameW(computerName, &computerName_len);
    return computerName;
}

int main()
{
    std::wcout << L"Username is : " << getUsername() << std::endl;
    std::wcout << L"Computer name is : " << getComputerName() << std::endl;
    return 0;
}

关于c++ - 无法获取和显示用户名的C++ Microsoft示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61275356/

相关文章:

c++ - 将指向局部变量的指针传递给另一个进程有时有效,但有时无效

windows - 关于 JvPatchFile 组件?

c++ - 我应该在非引用构造函数参数上手动调用 move 吗?

c# - X86 浏览器(cefsharp)无法在某些 X64 计算机上运行

c++ - 覆盖参数包声明和扩展位点

windows - 为什么当文件更改时 Perl 的 Win32::ChangeNotify 会触发两个事件?

c++ - 在 Windows 中停止线程

c++ - 如何在 C++ 中获取命令的输出?

c++ - 写 "::namespace::identifier"和 "namespace::identifier"有什么区别?

c++ - 在 C++ 类中重载全局函数 getline