Silverlight操作客户端注册表(优化)
前面贴出了Silverlight在OOB模式下操作客户端的注册表,后来自己又对代码进行了优化,将其封装成了一个操作类。
1.新建一个Silverlight类库,命名为ZKR.Silverlight.Core;
2.在类库下新建类,命名为LocalRegistryModel.cs;
3.实现代码:
- using System;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Ink;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- namespace ZKR.Silverlight.Core
- {
- /// <summary>
- /// 本地已安装软件的注册表对象(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall)
- /// </summary>
- public class LocalRegistryModel
- {
- /// <summary>
- /// 注册表名称
- /// </summary>
- public string RegName { get; set; }
- /// <summary>
- /// 软件名称
- /// </summary>
- public string DisplayName { get; set; }
- /// <summary>
- /// 软件版本
- /// </summary>
- public string DisplayVersion { get; set; }
- /// <summary>
- /// 发布者
- /// </summary>
- public string Publisher { get; set; }
- /// <summary>
- /// 安装目录
- /// </summary>
- public string InstallLocation { get; set; }
- /// <summary>
- /// 安装日期
- /// </summary>
- public string InstallDate { get; set; }
- /// <summary>
- /// 运行路径(可能是图标路径)
- /// </summary>
- public string DisplayIcon { get; set; }
- /// <summary>
- /// 卸载路径
- /// </summary>
- public string UninstallString { get; set; }
- public LocalRegistryModel()
- { }
- }
- }
4.在类库下新建类,命名为LocalMachine.cs;
5.实现代码:
- using System;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Ink;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- using System.Runtime.InteropServices.Automation;
- using System.Collections.ObjectModel;
- namespace ZKR.Silverlight.Core
- {
- /// <summary>
- /// 本地计算机对象(引用Microsoft.CSharp.dll)
- /// </summary>
- public class LocalMachine
- {
- #region 私有变量
- /// <summary>
- /// 注册表操作对象
- /// </summary>
- private static dynamic ObjReg = null;
- /// <summary>
- /// 已安装软件在注册表的路径
- /// </summary>
- private static string HKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
- #endregion
- /// <summary>
- /// 构造函数
- /// </summary>
- public LocalMachine()
- { }
- #region 公共方法
- /// <summary>
- /// 将该Silverlight应用程序加入开机自动启动列表
- /// </summary>
- /// <returns>程序执行过程中的提示信息</returns>
- public static string AddStartMenu()
- {
- string result = "";
- using (dynamic ShellApplication = AutomationFactory.CreateObject("Shell.Application")) //创建Shell对象
- {
- #region 获取程序菜单中的该Silverlight应用程序的快捷方式
- dynamic commonPrograms = ShellApplication.NameSpace(2); //获取本地开始菜单==》程序菜单
- string allUsersPath = commonPrograms.Self.Path;
- dynamic link = commonPrograms.ParseName(Deployment.Current.OutOfBrowserSettings.ShortName + ".lnk"); //获取当前Silverlight程序的快捷方式
- #endregion
- #region 获取桌面上的该Silverlight应用程序的快捷方式
- if (link == null)
- {
- commonPrograms = ShellApplication.NameSpace(0); //获取本地桌面菜单
- allUsersPath = commonPrograms.Self.Path;
- link = commonPrograms.ParseName(Deployment.Current.OutOfBrowserSettings.ShortName + ".lnk"); //获取当前Silverlight程序的快捷方式
- if (link == null)
- {
- result = "在程序菜单和桌面上未找到该程序的快捷方式,不能加载到启动项中.";
- }
- }
- #endregion
- #region 将快捷方式写入开机自动启动列表
- if (string.IsNullOrEmpty(result))
- {
- using (dynamic WShell = AutomationFactory.CreateObject("WScript.Shell"))
- {
- WShell.RegWrite(@"HKLM\Software\Microsoft\Windows\CurrentVersion\Run\" + Deployment.Current.OutOfBrowserSettings.ShortName, link.Path);
- result = "请重启你的机器,你的应用将被自动载入启动列表.";
- }
- }
- #endregion
- }
- return result;
- }
- /// <summary>
- /// 将该Silverlight应用程序从开机自动启动列表中移除
- /// </summary>
- /// <returns></returns>
- public static string RemoveStartMenu()
- {
- string result = "";
- using (dynamic WShell = AutomationFactory.CreateObject("WScript.Shell"))
- {
- try
- {
- WShell.RegDelete(@"HKLM\Software\Microsoft\Windows\CurrentVersion\Run\" + Deployment.Current.OutOfBrowserSettings.ShortName);
- result = "移除成功.";
- }
- catch
- {
- result = "没有找到该启动项.";
- }
- }
- return result;
- }
- /// <summary>
- /// 运行本地应用程序
- /// </summary>
- /// <param name="ApplicationPath">要运行的应用程序的路径</param>
- public static void RunApplication(string ApplicationPath)
- {
- if (!string.IsNullOrEmpty(ApplicationPath))
- {
- using (dynamic cmd = AutomationFactory.CreateObject("WScript.Shell"))
- {
- try { cmd.Exec(@ApplicationPath); }
- catch { }
- }
- }
- }
- /// <summary>
- /// 卸载本地应用程序
- /// </summary>
- /// <param name="ApplicationPath">要卸载的应用程序的路径</param>
- public static void UninstallApplication(string ApplicationPath)
- {
- if (!string.IsNullOrEmpty(ApplicationPath))
- {
- using (dynamic cmd = AutomationFactory.CreateObject("WScript.Shell"))
- {
- try { cmd.Exec(ApplicationPath); }
- catch { }
- }
- }
- }
- /// <summary>
- /// 获取本地已安装软件列表(忽略名称为空的软件信息)
- /// </summary>
- /// <returns>已安装软件列表</returns>
- public static ObservableCollection<LocalRegistryModel> GetInstallSoftware()
- {
- ObservableCollection<LocalRegistryModel> ListReg = new ObservableCollection<LocalRegistryModel>();
- dynamic ShellApplication = null;
- try
- {
- ShellApplication = AutomationFactory.CreateObject("WbemScripting.SWbemLocator"); //创建Shell对象
- }
- catch { return ListReg; }
- ObjReg = ShellApplication.ConnectServer(".", @"/root/default"); //连接到主机
- ObjRegObjReg = ObjReg.get("StdRegProv"); //创建注册表访问对象
- object[] InstalledSoft = GetSubKeys();
- if (InstalledSoft != null)
- {
- foreach (object SoftItem in InstalledSoft)
- {
- LocalRegistryModel reg = DisposeSubKey(SoftItem.ToString());
- if (reg != null && !string.IsNullOrEmpty(reg.DisplayName))
- {
- ListReg.Add(reg);
- }
- }
- }
- return ListReg;
- }
- #endregion
- #region 私有方法
- /// <summary>
- /// 获取注册表下的某一项的子项
- /// </summary>
- /// <returns>子项集合</returns>
- private static object[] GetSubKeys()
- {
- object[] result = null;
- dynamic RegMethod = ObjReg.Methods_("EnumKey"); //为Shell对象添加方法名称
- dynamic RegParam = RegMethod.InParameters.SpawnInstance_(); //为Shell对象添加参数
- RegParam.hDefKey = 0x80000002; //设置参数的主目录(HKLM)
- RegParam.sSubKeyName = HKey; //设置参数的子目录
- dynamic ReturnParam = ObjReg.ExecMethod_(RegMethod.Name, RegParam); //执行方法且获取返回值
- if (ReturnParam.ReturnValue == 0) //操作正常
- {
- try
- {
- result = (object[])ReturnParam.sNames; //获取子项集合
- }
- catch { }
- }
- return result;
- }
- /// <summary>
- /// 获取注册表对象
- /// </summary>
- /// <param name="SubKey">子项名称</param>
- /// <returns>注册表对象</returns>
- private static LocalRegistryModel DisposeSubKey(string SubKey)
- {
- LocalRegistryModel reg = new LocalRegistryModel(); //创建注册表对象
- dynamic RegMethod = ObjReg.Methods_("GetStringValue"); //为Shell对象添加方法名称
- dynamic RegParam = RegMethod.InParameters.SpawnInstance_(); //创建Shell对象的参数
- RegParam.hDefKey = 0x80000002; //设置参数的主目录(HKLM)
- RegParam.sSubKeyName = HKey + @"\" + SubKey; //设置参数的子目录
- reg.RegName = SubKey;
- RegParam.sValueName = "DisplayName"; //设置参数的子键名称
- dynamic ReturnParam = ObjReg.ExecMethod_(RegMethod.Name, RegParam); //执行方法且获取返回值
- reg.DisplayName = Convert.ToString(ReturnParam.sValue);
- if (string.IsNullOrEmpty(reg.DisplayName))
- {
- return reg;
- }
- RegParam.sValueName = "DisplayVersion";
- ReturnParam = ObjReg.ExecMethod_(RegMethod.Name, RegParam);
- reg.DisplayVersion = Convert.ToString(ReturnParam.sValue);
- RegParam.sValueName = "Publisher";
- ReturnParam = ObjReg.ExecMethod_(RegMethod.Name, RegParam);
- reg.Publisher = Convert.ToString(ReturnParam.sValue);
- RegParam.sValueName = "InstallLocation";
- ReturnParam = ObjReg.ExecMethod_(RegMethod.Name, RegParam);
- reg.InstallLocation = Convert.ToString(ReturnParam.sValue);
- RegParam.sValueName = "InstallDate";
- ReturnParam = ObjReg.ExecMethod_(RegMethod.Name, RegParam);
- reg.InstallDate = Convert.ToString(ReturnParam.sValue);
- RegParam.sValueName = "DisplayIcon";
- ReturnParam = ObjReg.ExecMethod_(RegMethod.Name, RegParam);
- reg.DisplayIcon = Convert.ToString(ReturnParam.sValue);
- RegParam.sValueName = "UninstallString";
- ReturnParam = ObjReg.ExecMethod_(RegMethod.Name, RegParam);
- reg.UninstallString = Convert.ToString(ReturnParam.sValue);
- return reg;
- }
- #endregion
- }
- }
6.新建Silverlight项目,添加ZKR.Silverlight.Core的引用;
7.xaml代码如下:
- <navigation:Page x:Class="LogInfoTest.Software"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d"
- xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
- d:DesignWidth="640" d:DesignHeight="480"
- xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
- Title="Software Page">
- <Grid x:Name="LayoutRoot" Background="White">
- <TextBlock Text="获取本机已安装软件的列表" FontSize="12" VerticalAlignment="Top" Margin="0,5,0,0" HorizontalAlignment="Left" Width="150" Height="20"></TextBlock>
- <Button x:Name="btnLoad" Content="读取" Click="btnLoad_Click" Width="50" Height="25" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="160,3,0,0"></Button>
- <sdk:DataGrid Margin="0,34,0,0" x:Name="DataGrid1" AutoGenerateColumns="False">
- <sdk:DataGrid.Columns>
- <sdk:DataGridTextColumn Binding="{Binding RegName, Mode=TwoWay}" CanUserReorder="False" Header="注册表名称" IsReadOnly="True" />
- <sdk:DataGridTextColumn Binding="{Binding DisplayName, Mode=TwoWay}" CanUserReorder="False" Header="软件名称" IsReadOnly="True" />
- <sdk:DataGridTextColumn Binding="{Binding DisplayVersion, Mode=TwoWay}" CanUserReorder="False" Header="软件版本" IsReadOnly="True" />
- <sdk:DataGridTextColumn Binding="{Binding Publisher, Mode=TwoWay}" CanUserReorder="False" Header="发布者" IsReadOnly="True" />
- <sdk:DataGridTextColumn Binding="{Binding InstallLocation, Mode=TwoWay}" CanUserReorder="False" Header="安装目录" IsReadOnly="True" />
- <sdk:DataGridTextColumn Binding="{Binding InstallDate, Mode=TwoWay}" CanUserReorder="False" Header="安装时间" IsReadOnly="True" />
- <sdk:DataGridTextColumn Binding="{Binding DisplayIcon, Mode=TwoWay}" CanUserReorder="False" Header="运行路径" IsReadOnly="True" />
- <sdk:DataGridTextColumn Binding="{Binding UninstallString, Mode=TwoWay}" CanUserReorder="False" Header="卸载路径" IsReadOnly="True" />
- <sdk:DataGridTemplateColumn Header="操作">
- <sdk:DataGridTemplateColumn.CellTemplate>
- <DataTemplate>
- <StackPanel Orientation="Horizontal">
- <Button x:Name="btnRun" Content="运行" DataContext="{Binding DisplayIcon}" Click="btnRun_Click" />
- <Button x:Uid="btnUninstall" Content="卸载" DataContext="{Binding UninstallString}" Click="btnUninstall_Click" Margin="5,0,0,0"/>
- </StackPanel>
- </DataTemplate>
- </sdk:DataGridTemplateColumn.CellTemplate>
- </sdk:DataGridTemplateColumn>
- </sdk:DataGrid.Columns>
- </sdk:DataGrid>
- </Grid>
- </navigation:Page>
- 8.xaml.cs代码:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- using System.Windows.Navigation;
- using System.Runtime.InteropServices.Automation;
- using ZKR.Silverlight.Core;
- using System.Collections.ObjectModel;
- namespace LogInfoTest
- {
- public partial class Software : Page
- {
- public Software()
- {
- InitializeComponent();
- }
- // 当用户导航到此页面时执行。
- protected override void OnNavigatedTo(NavigationEventArgs e)
- {
- }
- private void btnLoad_Click(object sender, RoutedEventArgs e)
- {
- this.DataGrid1.ItemsSource = LocalMachine.GetInstallSoftware();
- }
- private void btnRun_Click(object sender, RoutedEventArgs e)
- {
- LocalMachine.RunApplication(((Button)sender).DataContext.ToString());
- }
- private void btnUninstall_Click(object sender, RoutedEventArgs e)
- {
- LocalMachine.UninstallApplication(((Button)sender).DataContext.ToString());
- }
- }
- }