//////////////////////////////////////////////////////////////////////////////////////////////////// // Allocates required amount of memory and reads registry key value into ppBuf BOOL CConfigReader::ReadRegSZ ( HKEY hKey , LPCTSTR lpszValueName , TCHAR** ppBuf ) { // Find out the size of the buffer required to store the value DWORD dwBufSize = 0 ; LONG lRetVal = RegGetValue ( hKey , NULL , lpszValueName , RRF_RT_REG_SZ , NULL , NULL , &dwBufSize ) ; if ( ERROR_SUCCESS != lRetVal ) return FALSE ; // If value is not empty - allocate buffer and read value if ( dwBufSize > 0 ) { *ppBuf = new TCHAR [ dwBufSize ] ; if ( NULL == *ppBuf ) return FALSE ; lRetVal = RegGetValue ( hKey , NULL , lpszValueName , RRF_RT_REG_SZ , NULL , *ppBuf , &dwBufSize ) ; if ( ERROR_SUCCESS != lRetVal ) return FALSE ; } return TRUE ; }
static bool ReadPathFromRegistry(llvm::SmallString<128> &p) { HKEY hkey; bool res = false; // FIXME: Version number should be a define. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\ldc-developers\\LDC\\0.11.0"), NULL, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) { DWORD length; if (RegGetValue(hkey, NULL, _T("Path"), RRF_RT_REG_SZ, NULL, NULL, &length) == ERROR_SUCCESS) { TCHAR *data = static_cast<TCHAR *>(_alloca(length * sizeof(TCHAR))); if (RegGetValue(hkey, NULL, _T("Path"), RRF_RT_REG_SZ, NULL, data, &length) == ERROR_SUCCESS) { #if UNICODE std::string out; res = llvm::convertUTF16ToUTF8String( llvm::ArrayRef<UTF16>(reinterpret_cast<UTF16 *>(data), length), out); p = out; #else p = std::string(data); res = true; #endif } } RegCloseKey(hkey); } return res; }
static bool ReadPathFromRegistry(llvm::SmallString<128> &p) { HKEY hkey; bool res = false; // FIXME: Version number should be a define. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\ldc-developers\\LDC\\0.11.0"), NULL, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) { DWORD length; if (RegGetValue(hkey, NULL, _T("Path"), RRF_RT_REG_SZ, NULL, NULL, &length) == ERROR_SUCCESS) { std::vector<TCHAR> buffer; buffer.reserve(length); const auto data = buffer.data(); if (RegGetValue(hkey, NULL, _T("Path"), RRF_RT_REG_SZ, NULL, data, &length) == ERROR_SUCCESS) { #if UNICODE #if LDC_LLVM_VER >= 400 using UTF16 = llvm::UTF16; #endif std::string out; res = llvm::convertUTF16ToUTF8String( llvm::ArrayRef<UTF16>(reinterpret_cast<UTF16 *>(data), length), out); p = out; #else p = std::string(data); res = true; #endif } } RegCloseKey(hkey); } return res; }
static void pick_newest_sdk(HKEY key, char* name, search_t* p) { // SDKs ending with 'A' are .NET Framework. if(name[strlen(name) - 1] == 'A') return; DWORD path_len = MAX_PATH; DWORD version_len = MAX_VER_LEN; char new_path[MAX_PATH]; char new_version[MAX_VER_LEN]; if(RegGetValue(key, NULL, "InstallationFolder", RRF_RT_REG_SZ, NULL, new_path, &path_len) == ERROR_SUCCESS && RegGetValue(key, NULL, "ProductVersion", RRF_RT_REG_SZ, NULL, new_version, &version_len) == ERROR_SUCCESS) { uint64_t new_ver = get_version(new_version); if((strlen(p->version) == 0) || (new_ver > p->latest_ver)) { p->latest_ver = new_ver; strcpy(p->path, new_path); strcpy(p->version, new_version); strncpy(p->name, name, MAX_VER_LEN); } } }
void EjectKey::GetRemappedScanCode(BYTE &extendedScanCode, BYTE &scanCode) { DWORD regSize = 0; if (ERROR_SUCCESS == RegGetValue(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout"), _T("Scancode Map"), RRF_RT_REG_BINARY, nullptr, nullptr, ®Size)) { std::unique_ptr<BYTE[]> regkey(new BYTE[regSize]); if (ERROR_SUCCESS == RegGetValue(HKEY_LOCAL_MACHINE, _T("SYSTEM\\CurrentControlSet\\Control\\Keyboard Layout"), _T("Scancode Map"), RRF_RT_REG_BINARY, nullptr, regkey.get(), ®Size)) { scancode_map* sc_map = reinterpret_cast<scancode_map*>(regkey.get()); for (unsigned int i = 0; i< sc_map->no_of_mappings; i++) { mapping& current = sc_map->mappings[i]; if (current.fromExtScanCode == extendedScanCode && current.fromScanCode == scanCode) { extendedScanCode = current.toExtScanCode; scanCode = current.toScanCode; break; } } } } }
static bool GetStringValue(HKEY aBaseKey, const nsAString& aStrSubKey, const nsAString& aValueName, nsAString& aOutput) { const nsString& flatSubKey = PromiseFlatString(aStrSubKey); const nsString& flatValueName = PromiseFlatString(aValueName); LPCWSTR valueName = aValueName.IsEmpty() ? nullptr : flatValueName.get(); DWORD type = 0; DWORD numBytes = 0; LONG result = RegGetValue(aBaseKey, flatSubKey.get(), valueName, RRF_RT_ANY, &type, nullptr, &numBytes); if (result != ERROR_SUCCESS || (type != REG_SZ && type != REG_EXPAND_SZ)) { return false; } int numChars = (numBytes + 1) / sizeof(wchar_t); aOutput.SetLength(numChars); DWORD acceptFlag = type == REG_SZ ? RRF_RT_REG_SZ : RRF_RT_REG_EXPAND_SZ; result = RegGetValue(aBaseKey, flatSubKey.get(), valueName, acceptFlag, nullptr, aOutput.BeginWriting(), &numBytes); if (result == ERROR_SUCCESS) { // Truncate null terminator aOutput.SetLength(((numBytes + 1) / sizeof(wchar_t)) - 1); } return result == ERROR_SUCCESS; }
//////////////////////////////////////////////////////////////////////////////////////////////////// // Reads configuration of the specified quick launch item and fills the specified SHELLEXECUTEINFO // structure with information required to launch item. BOOL CConfigReader::Parse ( SHELLEXECUTEINFO* pExecInfo ) { // Try to find quick launch item configuration registry key HKEY hItemConfig ; TCHAR szConfigKey [ MAX_PATH ] ; HRESULT hr = StringCchPrintf ( szConfigKey , MAX_PATH , TEXT ( "%s\\%s" ) , g_szExecutorRegKey , m_lpszItemName ) ; if ( FAILED ( hr ) ) return FALSE ; LONG lRetVal = RegOpenKeyEx ( HKEY_CURRENT_USER , szConfigKey , 0 , KEY_READ , &hItemConfig ) ; if ( ERROR_SUCCESS != lRetVal ) return FALSE ; // Once configuration key was found let's read configuration into pExecInfo if ( !ReadRegSZ ( hItemConfig , g_szPathRegVal , &m_lpszPath ) ) // Path return FALSE ; if ( !ReadRegSZ ( hItemConfig , g_szParamsRegVal , &m_lpszParams ) ) // Command line parameters return FALSE ; DWORD dwBufSize = sizeof ( DWORD ) ; lRetVal = RegGetValue ( hItemConfig , NULL , g_szMonitorRegVal , RRF_RT_REG_DWORD , NULL , &m_dwMonitorIndex , &dwBufSize ) ; if ( ERROR_SUCCESS != lRetVal ) return FALSE ; lRetVal = RegGetValue ( hItemConfig , NULL , g_szWindowStateRegVal , RRF_RT_REG_DWORD , NULL , &m_dwWindowState , &dwBufSize ) ; if ( ERROR_SUCCESS != lRetVal ) return FALSE ; PopulateExecuteInformation ( pExecInfo ) ; return TRUE ; }
bool isProgramInAutostart() { HKEY key; LONG error; error = RegCreateKeyExW( HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, 0); if (error != ERROR_SUCCESS) { WIN_WARNING(L"cannot open autostart registry key: %s", getLastWindowsError().c_str()); return false; } wchar_t *buffer; DWORD buffersize = 0; #if (WINVER < _WIN32_WINNT_VISTA) DWORD type; error = RegQueryValueEx(key, Application::getName().data(), NULL, &type, NULL, &buffersize); if (type != REG_SZ) { WIN_WARNING(L"%s", L"autostart registry value has wrong type."); RegCloseKey(key); return false; } #else error = RegGetValue(key, NULL, Application::getName().data(), RRF_RT_REG_SZ, NULL, NULL, &buffersize); #endif if (error == ERROR_SUCCESS) { buffer = (wchar_t*)malloc(sizeof(wchar_t) * (buffersize+1)); #if (WINVER < _WIN32_WINNT_VISTA) error = RegQueryValueEx(key, Application::getName().data(), NULL, &type, (BYTE*)buffer, &buffersize); #else error = RegGetValue(key, NULL, Application::getName().data(), RRF_RT_REG_SZ, NULL, buffer, &buffersize); #endif } bool result; if (error != ERROR_SUCCESS) { if (error != ERROR_FILE_NOT_FOUND) { WIN_WARNING(L"cannot read autostart registry value: %s", getLastWindowsError().c_str()); } result = false; } else { result = (Application::getExecutablePath().compare(buffer) == 0); } RegCloseKey(key); return result; }
void HandleStartModuleChange() { DWORD temp; DWORD size = sizeof(temp); if(RegGetValue(hMonitoredKey, NULL, "StartModule", RRF_RT_REG_DWORD, NULL, &temp, &size) == ERROR_SUCCESS) isIngame = (temp == 1); }
PCTSTR CAbstractSettings::RegistryGet (HKEY hkey, PCTSTR pszKey) { DWORD dwType; union { TCHAR sz[MAX_PATH]; DWORD dw; } data; DWORD dwSize = sizeof (data); HRESULT hr; if ((hr = RegGetValue (hkey, NULL, pszKey, RRF_RT_REG_DWORD | RRF_RT_REG_SZ, &dwType, &data, &dwSize)) != ERROR_SUCCESS) { LOGDEBUG (TEXT ("Couldn't read registry key ") << pszKey << TEXT (", error ") << hr); } else { switch (dwType) { case REG_DWORD : dwSize = data.dw; StringCbPrintf (data.sz, sizeof (data.sz), TEXT ("%d"), dwSize); /* drop through */ case REG_SZ : return CachePut (pszKey, data.sz); default : LOGWARN (TEXT ("Unexpected type ") << dwType << TEXT (" in registry value ") << pszKey); break; } } return NULL; }
void OsDefaultBrowser(void) { HKEY hKey=0,hKey2=0; BOOL installed=false; char data[128]="IE"; DWORD dwret; DWORD dwDataSiz=sizeof(data); __try { dwret = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Clients\\StartMenuInternet", 0, KEY_READ, &hKey); if(dwret != ERROR_SUCCESS) __leave; RegGetValue(hKey, NULL, NULL, RRF_RT_REG_SZ, 0, &data, &dwDataSiz); } __finally { deb("def browser: %s", data); if(hKey) RegCloseKey(hKey); } }
int nvml_init (NVML_PTR *nvml) { if (!nvml) return (-1); memset (nvml, 0, sizeof (NVML_PTR)); #ifdef _WIN nvml->lib = hc_dlopen ("nvml.dll"); if (!nvml->lib) { DWORD BufferSize = 1024; char *Buffer = (char *) mymalloc (BufferSize); RegGetValue (HKEY_LOCAL_MACHINE, "SOFTWARE\\NVIDIA Corporation\\Global\\NVSMI", "NVSMIPATH", RRF_RT_ANY, NULL, (PVOID) Buffer, &BufferSize); strcat (Buffer, "\\nvml.dll"); nvml->lib = hc_dlopen (Buffer); myfree (Buffer); } #elif _POSIX nvml->lib = hc_dlopen ("libnvidia-ml.so", RTLD_NOW); #endif if (!nvml->lib) { if (data.quiet == 0) log_info ("WARNING: load NVML library failed, proceed without NVML HWMon enabled."); return (-1); } HC_LOAD_FUNC(nvml, nvmlErrorString, NVML_ERROR_STRING, NVML, 0) HC_LOAD_FUNC(nvml, nvmlInit, NVML_INIT, NVML, 0) HC_LOAD_FUNC(nvml, nvmlShutdown, NVML_SHUTDOWN, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetName, NVML_DEVICE_GET_NAME, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetHandleByIndex, NVML_DEVICE_GET_HANDLE_BY_INDEX, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetTemperature, NVML_DEVICE_GET_TEMPERATURE, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetFanSpeed, NVML_DEVICE_GET_FAN_SPEED, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetPowerUsage, NVML_DEVICE_GET_POWER_USAGE, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetUtilizationRates, NVML_DEVICE_GET_UTILIZATION_RATES, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetClockInfo, NVML_DEVICE_GET_CLOCKINFO, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetTemperatureThreshold, NVML_DEVICE_GET_THRESHOLD, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetCurrPcieLinkGeneration, NVML_DEVICE_GET_CURRPCIELINKGENERATION, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetCurrPcieLinkWidth, NVML_DEVICE_GET_CURRPCIELINKWIDTH, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetCurrentClocksThrottleReasons, NVML_DEVICE_GET_CURRENTCLOCKSTHROTTLEREASONS, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetSupportedClocksThrottleReasons, NVML_DEVICE_GET_SUPPORTEDCLOCKSTHROTTLEREASONS, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceSetComputeMode, NVML_DEVICE_SET_COMPUTEMODE, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceSetGpuOperationMode, NVML_DEVICE_SET_OPERATIONMODE, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetPowerManagementLimitConstraints, NVML_DEVICE_GET_POWERMANAGEMENTLIMITCONSTRAINTS, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceSetPowerManagementLimit, NVML_DEVICE_SET_POWERMANAGEMENTLIMIT, NVML, 0) HC_LOAD_FUNC(nvml, nvmlDeviceGetPowerManagementLimit, NVML_DEVICE_GET_POWERMANAGEMENTLIMIT, NVML, 0) return 0; }
/** * yfGetCygwinConfDir * * Gets the yaf config directory defined at INSTALLATION time on * Windows machines via reading the windows registry. * Caches the result in a file static. * * @return constant string with the data directory name * * @note must call yfCygwinClean to get rid of the memory * for the cached result */ const char * yfGetCygwinConfDir () { char *dataBuffer = NULL; DWORD bufferSize = 0; DWORD rc; if (NULL != winRegDataDir) { return winRegDataDir; } /* allocate memory for the initial buffer, likely this is big enough */ dataBuffer = (char *) malloc( sizeof(char) * INITIAL_BUFFER_SIZE); if (NULL == dataBuffer) { /* error couldn't allocate memory */ return NULL; } bufferSize = INITIAL_BUFFER_SIZE; /* keeping asking the registry for the value until we have a buffer big enough to hold it */ do { rc = RegGetValue ( HKEY_LOCAL_MACHINE, NETSA_WINDOWSREG_REGHOME, SILK_WINDOWSREG_DATA_DIR_KEY, RRF_RT_ANY, NULL, (PVOID)dataBuffer, &bufferSize); if (ERROR_MORE_DATA == rc) { dataBuffer = (char *) realloc (dataBuffer, (bufferSize + BUFFER_INCREMENT_SIZE)); if (NULL == dataBuffer) { return NULL; } bufferSize += BUFFER_INCREMENT_SIZE; } } while ( ERROR_MORE_DATA == rc); if ( ERROR_SUCCESS == rc ) { if ( 0 == bufferSize ) { /* What makes sense to do when we can't find the registry entry? In this case, we return a "sane" default for windows */ winRegDataDir = SILK_DEFAULT_CYGWIN_DATA_DIR; free(dataBuffer); return SILK_DEFAULT_CYGWIN_DATA_DIR; } else { winRegDataDir = windowsToCygwinPath(dataBuffer); free(dataBuffer); return winRegDataDir; } } else { return NULL; } }
void HandleBuildingComplete() { if(isIngame && isObs) { DWORD temp; DWORD size = sizeof(temp); if(RegGetValue(hMonitoredKey, NULL, "BuildingComplete", RRF_RT_REG_DWORD, NULL, &temp, &size) == ERROR_SUCCESS) isObs = !(temp == 1); } }
std::string regGetValue(HKEY hKey, const std::string& lpSubKey, LPCTSTR lpValueName, const std::string& defaultValue, DWORD dwFlags) { DWORD pdwType = REG_SZ; DWORD size = 512; char buffer[512]; if (RegOpenKeyEx( hKey, NULL, 0, KEY_READ | dwFlags, &hKey ) == ERROR_SUCCESS) { auto res = RegGetValue(hKey, lpSubKey.c_str(), lpValueName, RRF_RT_ANY, &pdwType, (LPBYTE)buffer, &size); //If the initial size is not enough to hold the value i.e. in case of a Reg_Multi_Sz value //Reinitialize a temp buffer with the new size if (res == ERROR_MORE_DATA) { std::vector<char>temp(size); res = RegGetValue(hKey, lpSubKey.c_str(), lpValueName, RRF_RT_ANY, &pdwType, reinterpret_cast<LPBYTE>(&temp[0]), &size); if (res == ERROR_SUCCESS) { RegCloseKey(hKey); return std::string(temp.data()); } } if (res == ERROR_SUCCESS) { // If the type of the key is REG_SZ, process it if (pdwType == REG_SZ) { RegCloseKey(hKey); return std::string(buffer); } //if the reg type is REG_DWORD, make a new call to get the value correctly if (pdwType == REG_DWORD) { DWORD dwValue = 0; res = RegGetValue(hKey, lpSubKey.c_str(), lpValueName, RRF_RT_ANY, &pdwType, (BYTE*)(DWORD)&dwValue, &size); if (res == ERROR_SUCCESS) { RegCloseKey(hKey); return std::to_string(dwValue); } } } } return defaultValue; }
std::wstring SteamLoader::GetSteamDllPath() { wchar_t pathString[512]; DWORD pathStringSize = sizeof(pathString); if (RegGetValue(HKEY_CURRENT_USER, L"Software\\Valve\\Steam\\ActiveProcess", STEAMCLIENT_DLL, RRF_RT_REG_SZ, nullptr, pathString, &pathStringSize) == ERROR_SUCCESS) { return pathString; } return L""; }
uint32_t SteamLoader::GetSteamProcessId() { DWORD pid; DWORD pidSize = sizeof(pid); if (RegGetValue(HKEY_CURRENT_USER, L"Software\\Valve\\Steam\\ActiveProcess", L"pid", RRF_RT_REG_DWORD, nullptr, &pid, &pidSize) == ERROR_SUCCESS) { return pid; } return 0; }
static bool ReadPathFromRegistry(llvm::SmallString<128> &p) { HKEY hkey; bool res = false; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\ldc-developers\\LDC\\0.11.0", //FIXME Version number should be a define NULL, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) { DWORD length; if (RegGetValue(hkey, NULL, "Path", RRF_RT_REG_SZ, NULL, NULL, &length) == ERROR_SUCCESS) { char *data = static_cast<char *>(_alloca(length)); if (RegGetValue(hkey, NULL, "Path", RRF_RT_REG_SZ, NULL, data, &length) == ERROR_SUCCESS) { p = std::string(data); res = true; } } RegCloseKey(hkey); } return res; }
int GetJavaTypeAndPath(int arch) { //Return 86 or 64 depending on which java is avialable. 0 means it isn't available. Also, set the reg key char buffer[20]; HKEY key; char base[] = "SOFTWARE\\JavaSoft\\Java Runtime Environment"; char regKeyPath[150]; long tmp = 0; int type = 0; DWORD shit = 20; if (arch == 64) { //Not a cure-all, but it seems if its in SysWow64, then its 64 bit available if (VerifyFileExists("C:\\Windows\\Syswow64\\javaw.exe")) { type = 64;} } pathLen = 257; ZeroMemory(buffer, 20); //Now lets get the folder path, since launching from Windows\SysWow64\javaw.exe doesn't allow us to run in 64-bit mode //We'll also try to verify if we can run in 64 bit mode by seeing if its in Program Files (x86) on a 64-bit machine strcpy(regKeyPath, base); tmp = RegOpenKeyEx(HKEY_LOCAL_MACHINE, base,0, KEY_READ | KEY_WOW64_64KEY ,&key); if (tmp != ERROR_SUCCESS) { return 0;} tmp = RegGetValue(key, NULL,"CurrentVersion", RRF_RT_REG_SZ, NULL, (PVOID)&buffer, &shit); if (tmp != ERROR_SUCCESS) { return 0;} strcat(regKeyPath, "\\"); strcat(regKeyPath, buffer); tmp = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regKeyPath,0, KEY_READ | KEY_WOW64_64KEY ,&key); if (tmp != ERROR_SUCCESS) { return 0;} tmp = RegGetValue(key, NULL,"JavaHome", RRF_RT_REG_SZ, NULL, (PVOID)&javaBinPath, &pathLen); if (tmp != ERROR_SUCCESS) { return 0;} //Append the exe strcat(javaBinPath, "\\bin\\javaw.exe"); if (arch != 64) { arch = 86;} return arch; }
// RegUpdater // ------------------ // Usage: // RegUpdater [NetmonFullPath | -c] // If Netmon's full path is not provided, the autorun registry item will be removed // // Example // Enable AutoRun: RegUpdater "D:\Netmon.exe" // Disable AutoRun: RegUpdater -c int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR lpCmdLine, int nCmdShow) { HKEY hRunKey; BOOL bAutoRunExist = FALSE; // Open registry key if (RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &hRunKey) != 0 ) { return 1; } // See if an autorun item exists if (RegGetValue(hRunKey, 0, TEXT("Netmon"), RRF_RT_REG_SZ, 0, 0, 0) == 0 ) { bAutoRunExist = TRUE; } // Update key value if (lpCmdLine[0] == TEXT('-') && lpCmdLine[1] == TEXT('c') && lpCmdLine[2] == 0 ) // Disable AutoRun { if (bAutoRunExist ) { RegDeleteValue(hRunKey, TEXT("Netmon")); } else // No need to delete value { } } else if (lpCmdLine[0] != 0 )// Enable AutoRun { TCHAR cmd[MAX_PATH]; _stprintf_s(cmd, MAX_PATH, TEXT("\"%s\" -h"), lpCmdLine); RegSetValueEx(hRunKey, TEXT("Netmon"), 0, REG_SZ, (BYTE *)cmd, _tcslen(cmd) * sizeof(TCHAR) + 1); } else // No argument, do nothing { } // Close registry key RegCloseKey(hRunKey); // Exit return 0; }
DWORD regGetRegDwd(HKEY hKey, const std::string& keyName, LPCTSTR lpValueName, DWORD defaultValue, DWORD dwFlags) { DWORD pdwType = REG_DWORD; DWORD dwValue = 0; DWORD size = 512; if (RegOpenKeyEx( hKey, NULL, 0, KEY_READ | dwFlags, &hKey ) == ERROR_SUCCESS) { if (RegGetValue(hKey, keyName.c_str(), lpValueName, RRF_RT_ANY, &pdwType, (BYTE*)(DWORD)&dwValue, &size) == ERROR_SUCCESS) { RegCloseKey(hKey); return dwValue; } } return defaultValue; }
//Функция проверки значения реестра int CheckVal() { DWORD pcbData = sizeof(DWORD); DWORD data = 10; LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\TestDir",0,KEY_ALL_ACCESS,&phkResult); if(lResult != ERROR_SUCCESS) { if (lResult == ERROR_FILE_NOT_FOUND) { if(MessageBox(NULL,"Key Not Found. Create it?",NULL,MB_YESNO) == IDYES) { //Попытка создания ключа реестра lResult = RegCreateKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\TestDir",0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&phkResult,NULL); if(lResult != ERROR_SUCCESS) { MessageBox(NULL,"Error Create Key",NULL,MB_OK); return NULL; } else { MessageBox(NULL,"Key Created",NULL,MB_OK); lResult = RegSetValueEx(phkResult,"TestRuns",0,REG_DWORD,(BYTE*)&data,sizeof(DWORD)); } } } else { MessageBox(NULL,"Error Open",NULL,MB_OK); return NULL; } } else { lResult = RegGetValue(HKEY_LOCAL_MACHINE,"SOFTWARE\\TestDir","TestRuns",RRF_RT_REG_DWORD,NULL,&data,&pcbData); if (lResult != ERROR_SUCCESS) { lResult = RegSetValueEx(phkResult,"TestRuns",0,REG_DWORD,(BYTE*)&data,sizeof(DWORD)); } } return data; }
static bool find_registry_value(char *path, char *name, search_t* p) { bool success = false; HKEY key; // Try global installations then user-only. if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, 0, (KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE), &key) == ERROR_SUCCESS || RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, (KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE), &key) == ERROR_SUCCESS) { DWORD size = MAX_PATH; success = RegGetValue(key, NULL, name, RRF_RT_REG_SZ, NULL, p->path, &size) == ERROR_SUCCESS; } RegCloseKey(key); return success; }
bool isRegRun() { HKEY hKey; //打开指定子键 DWORD dwDisposition = REG_OPENED_EXISTING_KEY; // 如果不存在不创建 if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dwDisposition) != ERROR_SUCCESS) return false; std::string filename = XFile::getCurrentExeFileFullPath(); if (filename.size() >= 3) { memcpy(&filename[filename.size() - 3], &"lnk", 3); //filename[filename.size() - 3] = 'l'; //filename[filename.size() - 2] = 'n'; //filename[filename.size() - 1] = 'k'; } else return false; DWORD dataType = REG_SZ; DWORD dataSize = 1024; char tmpName[1024]; //读取注册表中该键的键值,如果已经相同则不重复设置。 #if (_WIN32_WINNT >= 0x0601) //这个方法XP下不支持 if (RegGetValue(hKey, NULL, XEG.m_windowData.windowTitle.c_str(), RRF_RT_REG_SZ, &dataType, tmpName, &dataSize) == ERROR_SUCCESS) #else if (RegQueryValueEx(hKey, XEG.m_windowData.windowTitle.c_str(), NULL, &dataType, (LPBYTE)tmpName, &dataSize) == ERROR_SUCCESS) #endif { RegCloseKey(hKey); //下面判断字符串是否相同 //if(dataSize - 1 != filename.size()) return false; return XFile::fileNameCompare(tmpName, filename.c_str()); } // 关闭子键句柄 RegCloseKey(hKey); return false; }
void ComplexShapeInit(HWND hWnd) { int i; HWND hItem; hItem = GetDlgItem(hWnd, IDC_TOOL_SIZE); for (i = 0; i < ITEM_CNT(TOOL_SIZES); i++) ComboBox_AddString(hItem, TOOL_SIZES[i].str); hItem = GetDlgItem(hWnd, IDC_CUT_SPEED); for (i = 0; i < ITEM_CNT(CUT_SPEED); i++) ComboBox_AddString(hItem, CUT_SPEED[i].str); HKEY hKey; if (RegOpenKey(HKEY_CURRENT_USER, L"SOFTWARE", &hKey) == ERROR_SUCCESS) { DWORD cbData = sizeof(g_Params); if (RegGetValue(hKey, L"WinCNC", L"ComplexShape", RRF_RT_REG_BINARY, NULL, &g_Params, &cbData) == ERROR_SUCCESS) { return; } } ShapeInitToolInfo(&g_Params.tool); }
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hInstance); UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); UNREFERENCED_PARAMETER(nCmdShow); DWORD dwType; LONG lResult; // Retrieve the current jre version to get at the path TCHAR szCurrentVersion[32]; DWORD dwLenCurrentVersion = sizeof(szCurrentVersion) / sizeof(TCHAR); lResult = RegGetValue(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\JavaSoft\\Java Runtime Environment"), _T("CurrentVersion"), RRF_RT_REG_SZ, &dwType, szCurrentVersion, &dwLenCurrentVersion); if (lResult != ERROR_SUCCESS) { MessageBox(NULL, _T("Unable to locate HKEY_LOCAL_MACHINE\\SOFTWARE\\JavaSoft\\Java Runtime Environment\\CurrentVersion"), _T("Error"), MB_OK | MB_ICONERROR); return 1; } TCHAR szJavaHomePath[MAX_PATH] = _T("SOFTWARE\\JavaSoft\\Java Runtime Environment\\"); StrCat(szJavaHomePath, szCurrentVersion); // Build the location of javaw.exe TCHAR szJavaHome[MAX_PATH]; DWORD dwLenJavaHome = sizeof(szJavaHome) / sizeof(TCHAR); lResult = RegGetValue(HKEY_LOCAL_MACHINE, szJavaHomePath, _T("JavaHome"), RRF_RT_REG_SZ, &dwType, szJavaHome, &dwLenJavaHome); if (lResult != ERROR_SUCCESS) { MessageBox(NULL, _T("Unable to locate JavaHome key"), _T("Error"), MB_OK | MB_ICONERROR); return 2; } StrCat(szJavaHome, _T("\\bin\\javaw.exe")); TCHAR szMyPath[MAX_PATH]; GetModuleFileName(NULL, szMyPath, MAX_PATH); PathRemoveArgs(szMyPath); PathRemoveExtension(szMyPath); // Build the command line we will pass to javaw.exe TCHAR szExec[MAX_PATH] = _T(""); StrCat(szExec, _T("javaw.exe -jar \"")); StrCat(szExec, szMyPath); StrCat(szExec, _T(".jar\"")); // Execute javaw with the command line STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); BOOL bSuccess = CreateProcess(szJavaHome, szExec, NULL, NULL, FALSE, NULL, NULL, NULL, &si, &pi); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); if (!bSuccess) { MessageBox(NULL, _T("Unable to execute javaw.exe"), _T("Error"), MB_OK | MB_ICONERROR); return 3; } return 0; }
} return S_OK; } // Looks up a given registry key in this application's Settings space // (analogous to CWinApp::GetProfileInt()), converting it to a // (boolean) PROPVARIANT which is returned in *out. Uses the given // default value if the registry key cannot be loaded. static HRESULT RegKeyToProperty(const char *regkey, bool default, PROPVARIANT *out) { DWORD bsize = sizeof(DWORD), enabled; LONG code; code = RegGetValue(HKEY_CURRENT_USER, "Software\\MIT\\MIT Kerberos\\Settings", regkey, RRF_RT_DWORD, NULL, &enabled, &bsize); if (code == ERROR_FILE_NOT_FOUND) { code = ERROR_SUCCESS; enabled = default ? 1 : 0; } if (FAILED(code) || bsize != sizeof(enabled)) return E_FAIL; return UIInitPropertyFromBoolean(UI_PKEY_BooleanValue, enabled, out); } // Called by the framework when the value of a property needs to be // re-evaluated, e.g., if it has been explicitly invalidated, or at // program startup. This is the way to specify the initial/default // state for ribbon elements which have state, such as checkboxes. // The registry values which are modified by the MFC checkbox
INT_PTR CALLBACK SysConfProc(HWND hDlgWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { HKEY hKey; WCHAR buffer[MAX_LOAD_STRING]; DWORD bufSize; WCHAR wszReg[] = { 'S','o','f','t','w','a','r','e','\\', 'M','i','c','r','o','s','o','f','t','\\','O','L','E','\\','\0' }; WCHAR wszEnableDCOM[] = { 'E','n','a','b','l','e','D','C','O','M','\0' }; WCHAR wszEnableRemote[] = { 'E','n','a','b','l','e', 'R','e','m','o','t','e','C','o','n','n','e','c','t','\0' }; WCHAR wszYes[] = { 'Y', '\0' }; WCHAR wszNo[] = { 'N', '\0' }; switch(uMsg) { case WM_INITDIALOG: if(RegOpenKey(HKEY_LOCAL_MACHINE, wszReg, &hKey) != ERROR_SUCCESS) RegCreateKey(HKEY_LOCAL_MACHINE, wszReg, &hKey); bufSize = sizeof(buffer); if(RegGetValue(hKey, NULL, wszEnableDCOM, RRF_RT_REG_SZ, NULL, buffer, &bufSize) != ERROR_SUCCESS) { bufSize = sizeof(wszYes); RegSetValueEx(hKey, wszEnableDCOM, 0, REG_SZ, (BYTE*)wszYes, bufSize); } CheckDlgButton(hDlgWnd, IDC_ENABLEDCOM, buffer[0]=='Y' ? BST_CHECKED : BST_UNCHECKED); bufSize = sizeof(buffer); if(RegGetValue(hKey, NULL, wszEnableRemote, RRF_RT_REG_SZ, NULL, buffer, &bufSize) != ERROR_SUCCESS) { bufSize = sizeof(wszYes); RegSetValueEx(hKey, wszEnableRemote, 0, REG_SZ, (BYTE*)wszYes, bufSize); } CheckDlgButton(hDlgWnd, IDC_ENABLEREMOTE, buffer[0]=='Y' ? BST_CHECKED : BST_UNCHECKED); RegCloseKey(hKey); return TRUE; case WM_COMMAND: switch(LOWORD(wParam)) { case IDOK: bufSize = sizeof(wszYes); RegOpenKey(HKEY_LOCAL_MACHINE, wszReg, &hKey); RegSetValueEx(hKey, wszEnableDCOM, 0, REG_SZ, IsDlgButtonChecked(hDlgWnd, IDC_ENABLEDCOM) == BST_CHECKED ? (BYTE*)wszYes : (BYTE*)wszNo, bufSize); RegSetValueEx(hKey, wszEnableRemote, 0, REG_SZ, IsDlgButtonChecked(hDlgWnd, IDC_ENABLEREMOTE) == BST_CHECKED ? (BYTE*)wszYes : (BYTE*)wszNo, bufSize); RegCloseKey(hKey); EndDialog(hDlgWnd, IDOK); return TRUE; case IDCANCEL: EndDialog(hDlgWnd, IDCANCEL); return TRUE; } } return FALSE; }
/* * Get the current latency timer value for ftdi devices. * return value read on success or -1 if any error occurs. */ jint get_latency_timer_value(JNIEnv *env, jstring comPortName) { const jchar* port_name = NULL; int x = 0; BOOL ret = FALSE; LONG status = 0; DWORD error_code = 0; DWORD size = 0; DWORD regproptype; DWORD charbuffer_size = 0; DWORD driver_name_size = 0; ULONG buffer_size = 0; DWORD usb_member_index = 0; HDEVINFO usb_dev_info_set; SP_DEVINFO_DATA usb_dev_instance; ULONG devprop_buffer_size = 0; DEVPROPTYPE proptype; CONFIGRET cmret = 0; DEVINST firstchild = 0; DEVINST next_sibling = 0; DEVINST current_sibling = 0; DWORD timer_value; DWORD timervalue_size; /* size of these buffers is hardcoded in functions using them */ TCHAR buffer[1024]; TCHAR devprop_buffer[1024]; TCHAR keybuf[1024]; TCHAR charbuffer[128]; char cmerror[256]; /* extract com port name to match (as an array of Unicode characters) */ port_name = (*env)->GetStringChars(env, comPortName, JNI_FALSE); if ((port_name == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { throw_serialcom_exception(env, 3, 0, E_GETSTRUTFCHARSTR); return -1; } /* get information set for all usb devices matching the GUID */ usb_dev_info_set = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (usb_dev_info_set == INVALID_HANDLE_VALUE) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL); return -1; } /* enumerate all devices in this information set */ usb_member_index = 0; while (1) { ZeroMemory(&usb_dev_instance, sizeof(usb_dev_instance)); usb_dev_instance.cbSize = sizeof(usb_dev_instance); /* from information set, get device by index */ ret = SetupDiEnumDeviceInfo(usb_dev_info_set, usb_member_index, &usb_dev_instance); if (ret == FALSE) { error_code = GetLastError(); if (error_code == ERROR_NO_MORE_ITEMS) { break; } else { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(error_code), NULL); return -1; } } /* for this device find its instance ID (USB\VID_04D8&PID_00DF\000098037) * this is variable 'Device Instance Path' in device manager. */ memset(buffer, '\0', 1024); ret = SetupDiGetDeviceInstanceId(usb_dev_info_set, &usb_dev_instance, buffer, 1024, &size); if (ret == FALSE) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL); return -1; } cmret = CM_Get_Child(&firstchild, usb_dev_instance.DevInst, 0); if (cmret != CR_SUCCESS) { if (cmret == CR_NO_SUCH_DEVNODE) { /* this device does not have any child, so check if this device itself is a "Ports" class device or not */ memset(devprop_buffer, '\0', 1024); ret = SetupDiGetDeviceRegistryProperty(usb_dev_info_set, &usb_dev_instance, SPDRP_CLASSGUID, ®proptype, (BYTE *)devprop_buffer, sizeof(devprop_buffer), &size); if (ret == FALSE) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, HRESULT_FROM_SETUPAPI(GetLastError()), NULL); return -1; } /* match GUID */ ret = _tcsicmp(devprop_buffer, TEXT("{4D36E978-E325-11CE-BFC1-08002BE10318}")); if (ret != 0) { usb_member_index++; continue; } /* reaching here means that the device is COM port device (CDC/ACM), get its COM port name/number * HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS\VID_VID+PID_PID+Serial_Number\0000\DeviceParameters\PortName * HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_VID+PID_PID\Serial_Number\DeviceParameters\PortName */ memset(keybuf, '\0', 1024); _stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s\\Device Parameters"), buffer); charbuffer_size = sizeof(charbuffer); memset(charbuffer, '\0', 128); status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("PortName"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size); if (status != ERROR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, GetLastError(), NULL); return -1; } /* match port name */ ret = _tcsicmp(charbuffer, port_name); if (ret != 0) { usb_member_index++; continue; } /* HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\FTDIBUS\VID_VID+PID_PID+Serial_Number\0000\DeviceParameters\LatencyTimer */ status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("LatencyTimer"), RRF_RT_REG_DWORD, NULL, &timer_value, &timervalue_size); if (status != ERROR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, status, NULL); return -1; } SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); return (jint)timer_value; }else { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); _snprintf_s(cmerror, 256, 256, "CM_Get_DevNode_Registry_Property CR_xxxx error code : 0x%X\0", cmret); throw_serialcom_exception(env, 3, 0, cmerror); return -1; } } /* reaching here means that this USB device has at-least one child device node, examine child now */ devprop_buffer_size = sizeof(devprop_buffer); memset(devprop_buffer, '\0', sizeof(devprop_buffer)); cmret = CM_Get_DevNode_Registry_Property(firstchild, CM_DRP_CLASSGUID, &proptype, (PVOID)devprop_buffer, &devprop_buffer_size, 0); if (cmret != CR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); _snprintf_s(cmerror, 256, 256, "CM_Get_DevNode_Registry_Property CR_xxxx error code : 0x%X\0", cmret); throw_serialcom_exception(env, 3, 0, cmerror); return -1; } /* match GUID */ ret = _tcsicmp(devprop_buffer, TEXT("{4D36E978-E325-11CE-BFC1-08002BE10318}")); if (ret == 0) { /* reaching here means that the child device is COM port device (CDC/ACM), get its COM port name/number */ memset(buffer, '\0', 1024); cmret = CM_Get_Device_ID(firstchild, buffer, 1024, 0); if (cmret != CR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); _snprintf_s(cmerror, 256, 256, "CM_Get_Device_ID CR_xxxx error code : 0x%X\0", cmret); throw_serialcom_exception(env, 3, 0, cmerror); return -1; } memset(keybuf, '\0', 1024); _stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s\\Device Parameters"), buffer); charbuffer_size = sizeof(charbuffer); memset(charbuffer, '\0', 128); status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("PortName"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size); if (status != ERROR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, GetLastError(), NULL); return -1; } /* match port name */ ret = _tcsicmp(charbuffer, port_name); if (ret == 0) { status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("LatencyTimer"), RRF_RT_REG_DWORD, NULL, &timer_value, &timervalue_size); if (status != ERROR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, GetLastError(), NULL); return -1; } /* clean up and return timer value found */ SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); return (jint)timer_value; } } /* reaching here means first child of this USB device was not CDC/ACM interface, need to iterate over all the interfaces (siblings) this device has examining them for matching our criteria */ current_sibling = firstchild; while (1) { cmret = CM_Get_Sibling(&next_sibling, current_sibling, 0); if (cmret != CR_SUCCESS) { if (cmret == CR_NO_SUCH_DEVNODE) { /* done iterating over all interfaces, move to next examine next USB device */ break; } else { SetupDiDestroyDeviceInfoList(usb_dev_info_set); _snprintf_s(cmerror, 256, 256, "CM_Get_Sibling failed with CR_xxxx error code : 0x%X\0", cmret); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 3, 0, cmerror); return -1; } } /* reaching here means USB device has more than 1 interfaces, get class of this interface (sibling) */ devprop_buffer_size = sizeof(devprop_buffer); memset(devprop_buffer, '\0', sizeof(devprop_buffer)); cmret = CM_Get_DevNode_Registry_Property(next_sibling, CM_DRP_CLASSGUID, &proptype, (VOID *)devprop_buffer, &devprop_buffer_size, 0); if (cmret != CR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); _snprintf_s(cmerror, 256, 256, "CM_Get_DevNode_Registry_Property failed with CR_xxxx error code : 0x%X\0", cmret); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 3, 0, cmerror); return -1; } /* match GUID for this sibling */ ret = _tcsicmp(devprop_buffer, TEXT("{4D36E978-E325-11CE-BFC1-08002BE10318}")); if (ret != 0) { /* this interface is not CDC/ACM, loop over to next interface */ current_sibling = next_sibling; continue; } /* reaching here means that this sibling (interface) is a CDC/ACM type, get its COM port name/number */ buffer_size = (ULONG)_tcslen(buffer); memset(buffer, '\0', 1024); cmret = CM_Get_Device_ID(next_sibling, buffer, 1024, 0); if (cmret != CR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); _snprintf_s(cmerror, 256, 256, "CM_Get_Device_ID failed with CR_xxxx error code : 0x%X\0", cmret); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 3, 0, cmerror); return -1; } memset(keybuf, '\0', 1024); _stprintf_s(keybuf, 1024, TEXT("SYSTEM\\CurrentControlSet\\Enum\\%s\\Device Parameters"), buffer); charbuffer_size = sizeof(charbuffer); memset(charbuffer, '\0', 128); status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("PortName"), RRF_RT_REG_SZ, NULL, (PVOID)charbuffer, &charbuffer_size); if (status != ERROR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, GetLastError(), NULL); return -1; } /* match port name */ ret = _tcsicmp(charbuffer, port_name); if (ret == 0) { status = RegGetValue(HKEY_LOCAL_MACHINE, keybuf, TEXT("LatencyTimer"), RRF_RT_REG_DWORD, NULL, &timer_value, &timervalue_size); if (status != ERROR_SUCCESS) { SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 4, GetLastError(), NULL); return -1; } /* clean up and return timer value found */ SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); return (jint)timer_value; } /* set this sibling as base sibling for fetching next sibling, loop over to get and check next interface (sibling) */ current_sibling = next_sibling; } /* increment to get and examine the next usb device for COM ports class */ usb_member_index++; } /* reaching here means that probably given com port does not represent ftdi device or does not exist at all */ SetupDiDestroyDeviceInfoList(usb_dev_info_set); (*env)->ReleaseStringChars(env, comPortName, port_name); throw_serialcom_exception(env, 3, 0, E_NOTFTDIPORT); return -1; }
/* * CopEnumInterfaces * * Purpose: * * Remember list of available interfaces, excluding IUnknown. * */ BOOL CopEnumInterfaces( _In_ INTERFACE_INFO_LIST *InterfaceList ) { BOOL bResult = FALSE; HKEY hKey = NULL; LRESULT lRet; RPC_STATUS RpcStatus = 0; LPWSTR lpKeyName = NULL; SIZE_T k; DWORD i, cSubKeys = 0, cMaxLength = 0, cchKey; IID iid; INTERFACE_INFO *infoBuffer; __try { lRet = RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT("Interface"), 0, KEY_READ, &hKey); if (lRet != ERROR_SUCCESS) __leave; lRet = RegQueryInfoKey(hKey, NULL, NULL, NULL, &cSubKeys, &cMaxLength, NULL, NULL, NULL, NULL, NULL, NULL); if ((lRet != ERROR_SUCCESS) || (cSubKeys == 0)) __leave; infoBuffer = (INTERFACE_INFO*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cSubKeys * sizeof(INTERFACE_INFO)); if (infoBuffer == NULL) __leave; cMaxLength = (DWORD)((cMaxLength + 1) * sizeof(WCHAR)); lpKeyName = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cMaxLength); if (lpKeyName == NULL) __leave; for (k = 0, i = 0; i < cSubKeys; i++) { cchKey = (DWORD)(cMaxLength / sizeof(WCHAR)); if (RegEnumKeyEx(hKey, i, lpKeyName, &cchKey, NULL, NULL, NULL, NULL) == ERROR_SUCCESS) { if (IIDFromString(lpKeyName, &iid) == S_OK) { //skip IUnknown if (UuidCompare((UUID*)&iid, (UUID*)&IID_IUnknown, &RpcStatus) == 0) continue; cchKey = MAX_PATH * sizeof(WCHAR); infoBuffer[k].iid = iid; RegGetValue(hKey, lpKeyName, TEXT(""), RRF_RT_REG_SZ, NULL, (LPWSTR)&infoBuffer[k].szInterfaceName, &cchKey); k++; } } } InterfaceList->cEntries = (ULONG)k; InterfaceList->List = infoBuffer; bResult = TRUE; } __finally { if (hKey) RegCloseKey(hKey); if (lpKeyName) HeapFree(GetProcessHeap(), 0, lpKeyName); } return bResult; }