此方法的实例代码整理自MSDN,关键函数GetComputerName。 #include <Windows.h> #include <tchar.h> #include <stdio.h> #define INFO_BUFFER_SIZE 32767 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 ); } int main() { TCHAR infoBuf[INFO_BUFFER_SIZE]; DWORD bufCharCount = INFO_BUFFER_SIZE; if( !GetComputerName( infoBuf, &bufCharCount ) ) { printError( TEXT("GetComputerName") ); } _tprintf( TEXT("/nComputer name: %s/n"), infoBuf ); return 0; } 运行结果: