WinForm只能运行一个实例,存在则激活
思路
通过Process类获取当前运行的实例,存在时通过User32.dll接口激活窗口。
MainHelper
public class MainHelper
{
public static Process RunningInstance(string location)
{
var current = Process.GetCurrentProcess();
var processes = Process.GetProcessesByName(current.ProcessName);
foreach (Process process in processes)
{
if (process.Id != current.Id)
{
if (location.Replace("/", @"\") == current.MainModule.FileName)
{
return process;
}
}
}
return null;
}
public static void Active(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, 3);
SetForegroundWindow(instance.MainWindowHandle);
}
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
}
调用示例
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var location = Assembly.GetExecutingAssembly().Location;
var instance = MainHelper.RunningInstance(location);
if (instance != null)
{
MainHelper.Active(instance);
}
else
{
Application.Run(new Form1());
}
}