单例-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;
});

}
}

最终效果:

 

 

 

 

posted @   丹心石  阅读(147)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示