C# 多线程读取注册表,加载至TreeView

时间:2021-05-19

复制代码 代码如下:
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);
}
}
}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章