Sep 112010

This function will return the system name for the computer you’re on.  It just fishes it out of the registry, but it is handy if you need that information for displaying in your UI or using for other purposes.  I use it to build job IDs that are unique since the system name can’t be duplicated on the same network.

//
//	Returns the system network name
//	looks like \\name
//
CString GetSystemName()
{
	long result;
	HKEY mainKey;
	result = RegOpenKeyEx(
		HKEY_LOCAL_MACHINE,
		_T("SYSTEM\\CurrentControlSet\\Control\\ComputerName\\ComputerName"),
		0,
		KEY_READ,
		&mainKey
	);
	TCHAR nameData[_MAX_PATH];
	DWORD nameType;
	DWORD nameDataSize;
	CString cs;
	if (result == ERROR_SUCCESS) {
		nameDataSize = sizeof nameData;
		LONG ret = RegQueryValueEx(mainKey, _T("ComputerName"), NULL, &nameType,
                    (unsigned char *)nameData, &nameDataSize);
		if (ret==ERROR_SUCCESS && nameType==REG_SZ) {
			cs = nameData;
		}
		RegCloseKey(mainKey);
	}
	return DOUBLE_SLASH + cs;
}

Leave a Reply

(required)

(required)