代碼如下:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
namespace 星空個性化助手
{
public partial class Form1 : Form
{
private delegate void LoadTreeView左側( TreeNode node );//聲明委托類型
public Form1()
{
InitializeComponent ();
}
private void Form1_Load( object sender , EventArgs e )
{
Thread thread = new Thread (new ThreadStart (ReadAllReg));
thread.Start ();
}
/// <summary>
/// 讀取注冊表
/// </summary>
private void ReadAllReg()
{
LoadTreeView左側 loadTreeView = new LoadTreeView左側 (SendToTreeView);
RegistryKey reg = Registry.ClassesRoot;
TreeNode node = new TreeNode ("HKEY_CLASSES_ROOT");
ReadRegistry (reg , node);
reg.Close ();
if( treeView左側.InvokeRequired )//將讀取的根加載至TreeView
treeView左側.BeginInvoke (loadTreeView , node);
else
{
treeView左側.Nodes.Add (node);
}
/*----------------------------------------------------*/
reg = Registry.CurrentUser;
node = new TreeNode ("HKEY_CURRENT_USER");
ReadRegistry (reg , node);
reg.Close ();
if( treeView左側.InvokeRequired )//將讀取的根加載至TreeView
treeView左側.BeginInvoke (loadTreeView , node);
else
{
treeView左側.Nodes.Add (node);
}
/*----------------------------------------------------*/
reg = Registry.LocalMachine;
node = new TreeNode ("HKEY_LOCAL_MACHINE");
ReadRegistry (reg , node);
reg.Close ();
if( treeView左側.InvokeRequired )//將讀取的根加載至TreeView
treeView左側.BeginInvoke (loadTreeView , node);
else
{
treeView左側.Nodes.Add (node);
}
/*----------------------------------------------------*/
reg = Registry.Users;
node = new TreeNode ("HKEY_USERS");
ReadRegistry (reg , node);
reg.Close ();
if( treeView左側.InvokeRequired )//將讀取的根加載至TreeView
treeView左側.BeginInvoke (loadTreeView , node);
else
{
treeView左側.Nodes.Add (node);
}
/*----------------------------------------------------*/
reg = Registry.CurrentConfig;
node = new TreeNode ("HKEY_CURRENT_CONFIG");
ReadRegistry (reg , node);
reg.Close ();
if( treeView左側.InvokeRequired )//將讀取的根加載至TreeView
treeView左側.BeginInvoke (loadTreeView , node);
else
{
treeView左側.Nodes.Add (node);
}
}
/// <summary>
/// 發送到TreeView
/// </summary>
/// <param name="node">TreeNode</param>
private void SendToTreeView( TreeNode node )
{
treeView左側.Nodes.Add (node);
treeView左側.Refresh ();
}
/// <summary>
/// 遞歸注冊表樹
/// </summary>
/// <param name="reg">注冊表起始點</param>
/// <param name="nodes">起始樹,將在它下面建立所有子結點</param>
internal void ReadRegistry( RegistryKey reg , TreeNode nodes )//遞歸注冊表樹
{
foreach( string names in reg.GetSubKeyNames () )
{
TreeNode node = new TreeNode (names);
try
{
RegistryKey r = reg.OpenSubKey (names , false);
if( r != null )
{
ReadRegistry (r , node);
r.Close ();
}
else
{
return;
}
}
catch( Exception err )
{
continue;
}
nodes.Nodes.Add (node);
}
}
}
}