1.自定义SingletonWindow类(此方法也适合于传统winform程序)
using System;
using System.Linq;
namespace NetWorld
{
public class SingletonWindow
{
public static System.Diagnostics.Process Process() //如果不适用附加属性也可以直接使用此函数
{
//判断单实例的方式有很多,如mutex,process,文件锁等,这里用的是process方式
var process = GetRunningInstance();
if (process != null)
{
HandleRunningInstance(process);
Environment.Exit(0);
}
return process;
}
[System.Runtime.InteropServices.DllImport("User32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
static System.Diagnostics.Process GetRunningInstance()
{
var current = System.Diagnostics.Process.GetCurrentProcess();
var processes = System.Diagnostics.Process.GetProcessesByName(current.ProcessName);
foreach (var process in processes)
{
if (process.Id != current.Id)
if (System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
return process;
}
return null;
}
static void HandleRunningInstance(System.Diagnostics.Process instance)
{
if (instance.MainWindowHandle != IntPtr.Zero)
{
SetForegroundWindow(instance.MainWindowHandle);
}
}
}
}
2.