c#多线程读取注册表 c#多线程的小例子

发布时间:2020-06-03编辑:脚本学堂
C#实现的多线程读取注册表的例子,并将注册表信息加载到TreeView中。

C#实现的多线程读取注册表的例子,并将注册表信息加载到TreeView中。
有需要的朋友可以参考下。

复制代码 代码示例:

/// <summary>
/// c#多线程读取注册表
/// </summary>
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>
///link:http://www.jb200.com
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);
}
}
}
}