C++中根据HKey查找当前打开的注册表路径Key Name

在StackOverFlow里找到的,一定要收藏起来。

#include <windows.h> #include <string>
typedef LONG NTSTATUS;
#ifndef STATUS_SUCCESS
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) #endif
#ifndef STATUS_BUFFER_TOO_SMALL
#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L) #endif
std::wstring GetKeyPathFromKKEY(HKEY key) {     std::wstring keyPath;     
if (key != NULL)     {         HMODULE dll = LoadLibrary(Lntdll.dll);         if (dll != NULL) {             typedef DWORD (__stdcall ZwQueryKeyType)(                 HANDLE  KeyHandle,                 int KeyInformationClass,                 PVOID  KeyInformation,                 ULONG  Length,                 PULONG  ResultLength);
            ZwQueryKeyType func 
= reinterpret_cast<ZwQueryKeyType>(::GetProcAddress(dll, ZwQueryKey));
            
if (func != NULL) {                 DWORD size = 0;                 DWORD result = 0;                 result = func(key, 300&size);                 if (result == STATUS_BUFFER_TOO_SMALL)                 {                     size = size + 2;                     wchar_t
 buffer = new (std::nothrow) wchar_t[size];                     if (buffer != NULL)                     {                         result = func(key, 3, buffer, size, &size);                         if (result == STATUS_SUCCESS)                         {                             buffer[size / sizeof(wchar_t)] = L\0;                             keyPath = std::wstring(buffer + 2);                         }
                        delete[] buffer;                     }                 }             }
            FreeLibrary(dll);         }     }     
return keyPath; }
int _tmain(int argc, _TCHAR* argv[]) {     HKEY key = NULL;     LONG ret = ERROR_SUCCESS;
    ret 
= RegOpenKey(HKEY_LOCAL_MACHINE, LSOFTWARE\Microsoft&key);     if (ret == ERROR_SUCCESS)     {         wprintf_s(LKey path for %p is ’%s’., key, GetKeyPathFromKKEY(key).c_str());             RegCloseKey(key);     }
    
return 0; }

输出:

Key path for 00000FDC is '\REGISTRY\MACHINE\SOFTWARE\Microsoft'.

[温馨提示]:该文章由原博客园导入而来,如排版效果不佳,请移步:http://www.cnblogs.com/coderzh/archive/2009/11/10/1599732.html

微信扫一扫交流

作者:CoderZh
微信关注:hacker-thinking (一个程序员的思考)
本文出处:https://blog.coderzh.com/2009/11/10/1599732/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。