WinForm如何與Windows注冊(cè)表交互

小億
85
2024-05-09 10:51:54

在WinForm中與Windows注冊(cè)表交互通常需要使用Microsoft.Win32命名空間中的Registry類。以下是一個(gè)簡(jiǎn)單的示例,演示如何使用Registry類讀取和寫(xiě)入注冊(cè)表中的值:

using Microsoft.Win32;

// 讀取注冊(cè)表中的值
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");
        }
    }
}

// 寫(xiě)入注冊(cè)表中的值
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"的注冊(cè)表項(xiàng)的值,并在消息框中顯示。WriteRegistryValue方法用于創(chuàng)建或打開(kāi)名為"MyApp"的注冊(cè)表項(xiàng),并寫(xiě)入一個(gè)值為"Hello, Registry!"的子項(xiàng)。您可以根據(jù)自己的需求進(jìn)一步擴(kuò)展和修改這些方法。

0