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.

创建WPF单实例应用程序

 

相关文章:

  • 2021-09-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-30
  • 2021-11-22
  • 2021-10-11
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-03-01
  • 2021-11-16
  • 2022-12-23
  • 2021-11-26
  • 2022-12-23
  • 2022-03-02
相关资源
相似解决方案