注册表项 getvalue 未获取最新值

Sai*_*Sai 5 c#

我试图通过HKCU\Keyboard Layout\Preload\1从我的应用程序中读取来获取当前用户最后使用的键盘布局。每次在控制面板中更改默认键盘时,我都可以看到上述位置的值发生变化(我可以通过打开 RegEdit 来看到这一点)。但由于某种原因,我的应用程序仍然读取旧值,而不考虑我可以在 RegEdit 上看到的最新刷新。

string KeyboardLayoutRegKey = "Keyboard Layout\\Preload";
pLastUsedKeyboard = RegistryAccessor.CurrentUser.OpenSubKey(KeyboardLayoutRegKey).GetValue("1").ToString(),
Run Code Online (Sandbox Code Playgroud)

当我将值从美国英语更改为法语时,注册表中的十六进制值从 409 更改为 40c,我可以在 RegEdit 中看到这一点,但我的应用程序仍然将其读取为 409,直到我重新启动?为什么要这样做?我的应用程序针对的是 AnyCPU。

编辑

/// <summary>
/// Provides access to the registry. 
/// </summary>
public class RegistryAccessor : IRegistryAccessor
{
    /// <summary>
    /// Contains information about the current user preferences. This field reads the Windows registry base key HKEY_CURRENT_USER.
    /// </summary>
    public IRegistryKey CurrentUser
    {
        get
        {
            return new RegistryKeyWrapper(Registry.CurrentUser);
        }
    }

    /// <summary>
    /// Contains the configuration data for the local machine. This field reads the Windows registry base key HKEY_LOCAL_MACHINE.
    /// </summary>
    public IRegistryKey LocalMachine
    {
        get
        {
            return new RegistryKeyWrapper(Registry.LocalMachine);
        }
    }
    /// <summary>
    /// Contains the configuration data for the Users. This field reads the Windows registry base key HKEY_USERS.
    /// </summary>
    public IRegistryKey Users
    {
        get
        {
            return new RegistryKeyWrapper(Registry.Users);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 1

如果不重新启动应用程序,则无法“刷新”注册表值。如果您需要在您的应用程序运行时在注册表项值发生更改时收到通知,您可以使用 WMI 来实现RegistryValueChangeEvent。您可以参考这个答案,它可以帮助您在应用程序中实现它