简体   繁体   English

如何访问注册表,并在C中循环键(提供示例C#代码)?

[英]How do I access the registry, and loop through keys in C (Example C# code provided)?

I basically want to perform the same functions as this code, but in C. 我基本上想要执行与此代码相同的功能,但在C中。

RegistryKey regAdapters = Registry.LocalMachine.OpenSubKey ( AdapterKey, true);
    string[] keyNames = regAdapters.GetSubKeyNames();
    char[] devGuid;
    foreach(string x in keyNames)
    {
        RegistryKey regAdapter = regAdapters.OpenSubKey(x);
        object id = regAdapter.GetValue("ComponentId");
        if (id != null && id.ToString() == "tap0801") devGuid = regAdapter.GetValue("NetCfgInstanceId").ToString();
    }

There's actually no recursion there. 那里实际上没有递归。 The code just opens a key under HKLM, enumerates all sub-keys, and looks for a particular named value. 代码只是在HKLM下打开一个键,枚举所有子键,并查找特定的命名值。 In outline, your C code would be made up from these Win32 API calls: 概括地说,您的C代码将由这些Win32 API调用组成:

HKEY hRegAdapters;
LONG res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AdapterKey, 0,
  KEY_READ, &hRegAdapters);
// error checking by testing res omitted

Now that you have opened the key you can enumerate sub keys: 现在您已经打开了密钥,您可以枚举子密钥:

for (DWORD Index=0; ; Index++)
{
    char SubKeyName[255];
    DWORD cName = 255;
    LONG res = RegEnumKeyEx(hRegAdapters, Index, SubKeyName, &cName, 
        NULL, NULL, NULL, NULL);
    if (res != ERROR_SUCCESS)
        break;
    // do something with Name
}

Now that you have the name of each sub-key, you can read the values with RegGetValue : 现在您拥有每个子键的名称,您可以使用RegGetValue读取值:

char Value[64];
DWORD cbData = 64;
LONG res = RegGetValue(hSubKey, SubKeyName, "ComponentId",
    RRF_RT_REG_SZ, NULL, Value, &cbData);
// check for errors now before using Value

RegGetValue is a convenience function added in Vista. RegGetValue是Vista中添加的便利功能。 If you need your code to run on XP then you'll have to call RegQueryValueEx instead. 如果您需要在XP上运行代码,那么您将不得不调用RegQueryValueEx That involves opening the "ComponentId" subkey first. 这涉及首先打开"ComponentId"子项。

Note that I've omitted all error checking and also ignored the issue of Unicode and called the ANSI APIs. 请注意,我省略了所有错误检查,也忽略了Unicode的问题并调用了ANSI API。 I'll leave all those details to you. 我会把所有这些细节留给你。

Remember to call RegCloseKey(hRegAdapters) when you have finished. 完成后,请记得调用RegCloseKey(hRegAdapters)

Refer to the MSDN documentation for all the gory details of how to access the registry. 有关如何访问注册表的所有详细信息,请参阅MSDN文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM