添加Microsoft.VisualBasic引用,头引用
using Microsoft.VisualBasic.ApplicationServices;
打开App.xaml.cs文件,将文件修改为如下
class Program
{
[STAThread]
static void Main(string[] args)
{
SingleInstanceApp a = new SingleInstanceApp();
a.Run(args);
}
}
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : System.Windows.Application
{
protected override void OnStartup(System.Windows.StartupEventArgs e)
{
base.OnStartup(e);
InitializeComponent();
}
}
public class SingleInstanceApp : WindowsFormsApplicationBase
{
App win = null;
public SingleInstanceApp()
{
this.IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
win = new App();
win.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
foreach (System.Windows.Window _win in win.Windows)
{
if (_win.Visibility == System.Windows.Visibility.Visible)
{
_win.Activate();
}
}
}
}
编译下,vs会告知有2个入口函数,定位到App.g.cs的main函数,直接删除掉就可以了~~以上代码通用,无需修改任何东西..当然,要写入自己的个性需求则自己改~~