使用用互斥量(System.Threading.Mutex):
?? ?同步基元,它只向一个线程授予对共享资源的独占访问权。在程序启动时候,请求一个互斥体,如果能获取对指定互斥的访问权,就职运行一个实例。
实例代码:
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
[DllImport("user32.dll ")]
//设置窗体置顶
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private static Mutex _m = null;
private static string currentProcess = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
/// <summary>
/// 只允许运行一个实例
/// </summary>
/// <param name="mutexName"></param>
/// <returns>true:已经存在实例 false:不存在实例</returns>
public static bool CheckRunOneInstance(string mutexName = null)
{
bool result = false;
bool mutexWasCreated = false;
try
{
bool requestInitialOwnership = true;
if (mutexName == null)
mutexName = currentProcess;
_m = new Mutex(requestInitialOwnership, mutexName, out mutexWasCreated);
if (!mutexWasCreated)
{
result = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
/// <summary>
/// 有程序运行,设置焦点
/// </summary>
private void Focus()
{
foreach (Process process in Process.GetProcesses())
{
try
{
if (process.ProcessName.ToLower() != currentProcess.ToLower())
continue;
IntPtr hwnd = process.MainWindowHandle;
if (hwnd != IntPtr.Zero)
{
SetForegroundWindow(hwnd);
ShowWindow(hwnd, 2);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void Application_Startup(object sender, StartupEventArgs e)
{
if(CheckRunOneInstance())
{
Focus();
System.Windows.Application.Current.Shutdown();
return;
}
else
{
new MainWindow().Show();
}
}
}
实例链接: