silverlight目前開發的應用,想做到系統內登出後自動重新啟動下 sllauncher.exe ,實現方式是通過WMI的COM介面,獲取到當前應用的執行命令列(CommandLine);並通過shell執行;程式碼如下:
#region Using Section using System; using System.Collections.Generic; using System.Runtime.InteropServices.Automation; using System.Windows; #endregion namespace KillSelf { public class ComObjectHelper { private static List<string> GetProcess() { var result = new List<string>(); try { dynamic objLocator = AutomationFactory.CreateObject("WbemScripting.SWbemLocator"); dynamic objWmiService = objLocator.ConnectServer(".", "root\\cimv2"); dynamic query = objWmiService.ExecQuery("Select * from Win32_Process"); foreach (dynamic o in query) { //string value = "ExecutablePath = " + o.CommandLine + "\r\n"; //Console.WriteLine(value); result.Add(o.CommandLine + ""); } return result; } catch (Exception ex) { MessageBox.Show("Get Process:" + ex.Message); } return null; } internal static void Exec(string cmdline) { try { dynamic cmd = AutomationFactory.CreateObject("WScript.Shell"); cmd.Run(cmdline, 1, false); } catch (Exception ex) { MessageBox.Show("Execute Process:" + ex.Message); } } public static SlProcess GetSelf() { string[] procs = GetProcess().ToArray(); foreach (string p in procs) { string cmdline = p.ToLower(); if (cmdline.IndexOf("sllauncher.exe", StringComparison.Ordinal) != -1) { return new SlProcess(cmdline); } } throw new NullReferenceException("未找到SLLauncher.exe程式"); } } public class SlProcess { public SlProcess(string cmdline) { CommandLine = cmdline; } public string CommandLine { get; set; } public SlProcess Run() { ComObjectHelper.Exec(CommandLine); return this; } public SlProcess Kill() { Application.Current.MainWindow.Close(); return this; } } }
呼叫部分:
private void Button_Click(object sender, RoutedEventArgs e) { if (!Application.Current.IsRunningOutOfBrowser) { MessageBox.Show("Not Running OutOfBrowser!!"); return; } ComObjectHelper.GetSelf().Run().Kill(); }