其他分享
首页 > 其他分享> > 单例-WPF

单例-WPF

作者:互联网

1.新建WPF项目,然后引用Microsoft.VisualBasic 

2.删除原生的App.xaml,建立WpfApp类,并使该类继承自Application,在该类中实现WPF MainWindow 窗体的创建工作


public class WpfApp:System.Windows.Application
{
private Action<string> SetTime;
private Timer timer = new Timer();
public WpfApp() {
timer.Interval = 1000;
timer.AutoReset = true;
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (SetTime != null)
{
SetTime(DateTime.Now.ToLongTimeString());
}
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ShowWindow();

}
public void ShowWindow()
{
MainWindow win = new WpfApp7.MainWindow();
SetTime += win.GetTime;  //向各个窗体广播消息
win.Show();
}
}

3.编写单实例包装类

public class SingleInstanceWrapper:Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
private WpfApp app;
public SingleInstanceWrapper()
{
IsSingleInstance = true; //是否允许单实例
}
protected override bool OnStartup(StartupEventArgs eventArgs)
{
// return base.OnStartup(eventArgs);
app = new WpfApp();
app.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
app.ShowWindow();
}
}

4.创建单线程启动类

public class Startup
{
[STAThread]
public static void Main(string[] args) {
SingleInstanceWrapper wrapper = new SingleInstanceWrapper();
wrapper.Run(args);
}
}

5.窗体类实现代码

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void GetTime(string time) {
this.Dispatcher.Invoke((Action)delegate {
this.Title = time;
});

}
}

最终效果:

 

 

 

 

标签:void,timer,MainWindow,eventArgs,单例,WPF,WpfApp,public
来源: https://www.cnblogs.com/sundh1981/p/16129878.html