您的位置:宽带测速网 > 网站建设 > WinForm如何与Windows注册表交互

WinForm如何与Windows注册表交互

2025-06-25 09:50来源:互联网 [ ]

在WinForm中与Windows注册表交互通常需要使用Microsoft.Win32命名空间中的Registry类。以下是一个简单的示例,演示如何使用Registry类读取和写入注册表中的值:

using Microsoft.Win32;// 读取注册表中的值private void ReadRegistryValue(){using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\MyApp")){if (key != null){object value = key.GetValue("MyValue");if (value != null){MessageBox.Show("Registry value: " + value.ToString());}else{MessageBox.Show("Registry value not found");}}else{MessageBox.Show("Registry key not found");}}}// 写入注册表中的值private void WriteRegistryValue(){using (RegistryKey key = Registry.CurrentUser.CreateSubKey("Software\\MyApp")){if (key != null){key.SetValue("MyValue", "Hello, Registry!");MessageBox.Show("Registry value written successfully");}else{MessageBox.Show("Error writing to registry");}}}

在上面的示例中,ReadRegistryValue方法用于读取名为"MyValue"的注册表项的值,并在消息框中显示。WriteRegistryValue方法用于创建或打开名为"MyApp"的注册表项,并写入一个值为"Hello, Registry!"的子项。您可以根据自己的需求进一步扩展和修改这些方法。