/// <summary> /// 通过类属性=>调试=>命令行参数执行相应的动作 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Application_Startup(object sender, StartupEventArgs e) { bool startMinmized = false; for (int i = 0; i < e.Args.Length; i++) { if (e.Args[i] == "/StartMinmized") startMinmized = true; } MainWindow win = new MainWindow(); if (startMinmized) { win.WindowState = WindowState.Minimized; win.Content = "当前命令参数为:" + e.Args[0]; } win.Show(); }
/// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { /// <summary> /// Mutex 在System.Threading命名空间中,成为同步基元,或者成为互斥元. /// 当创建一个引用程序类时,将同时创建一个系统范围内的命名的Mutex对象. /// 这个互斥单元在整个操作系统中都是可见的. /// </summary> Mutex mutex; protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); string mutexName = "SingleInstanceApplication"; bool CreatedNew; //判断是否已经创建相同实例名称的应用程序 mutex = new Mutex(true, mutexName, out CreatedNew); if (!CreatedNew) { MessageBox.Show("已经存在一个引用程序势力"); Shutdown(); } } }
namespace SingleInstanceWithCommunication { public class Startup { [STAThread] public static void Main(string[] args) { SingleApplicationBase sab = new SingleApplicationBase(); sab.Run(args); } } }
namespace SingleInstanceWithCommunicationhCommunication { public class SingleApplicationBase : WindowsFormsApplicationBase { public SingleApplicationBase() { //设置应用程序为单例程序 this.IsSingleInstance = true; } //SingleInstanceWithCommunication.App App wpfApp; protected override bool OnStartup(StartupEventArgs eventArgs) { wpfApp = new App(); wpfApp.Run(); return false; } protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) { //当前程序开启后,继续开启新程序会触发OnStartupNextInstance事件,程序作出相应动作. //可以获取当前参数在已开启的程序中操作相应动作. base.OnStartupNextInstance(eventArgs); if (eventArgs.CommandLine.Count > 0) wpfApp.ShowWindowText(eventArgs.CommandLine[0]); } } }
namespace SingleInstanceWithCommunication { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); MainWindow win = new SingleInstanceWithCommunication.MainWindow(); this.MainWindow = win; win.Show(); if (e.Args.Length > 0) ShowWindowText(e.Args[0]); } public void ShowWindowText(string fileName) { Window1 win = new Window1(); win.Title = fileName; ((MainWindow)this.MainWindow).lstBox.Items.Add(fileName); win.Owner = this.MainWindow; win.LoadFile(fileName); win.Show(); } } }
原文:http://www.cnblogs.com/zero0r1/p/7420777.html