控制同一exe程序打开多次
1.新建一个SingleInstance类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace NetChange
{
class SingleInstance
{
[DllImport("User32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
[DllImport("User32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private const int WS_SHOWNORMAL = 1;
public static Process GetRunningInstance()
{
Process currentProcess = Process.GetCurrentProcess();
string currentFileName = currentProcess.MainModule.FileName;
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
foreach (Process process in processes)
{
if (process.MainModule.FileName == currentFileName)
{
if (process.Id != currentProcess.Id)
return process;
}
}
return null;
}
public static bool HandleRunningInstance(Process instance)
{
ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
return SetForegroundWindow(instance.MainWindowHandle);
}
public static bool HandleRunningInstance()
{
Process p = GetRunningInstance();
if (p != null)
{
HandleRunningInstance(p);
return true;
}
return false;
}
}
}
2.在program.cs 修改代码如下:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace NetChange
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//===定义SingleInstance类,实现应用运行唯一性判断==
if (SingleInstance.HandleRunningInstance() == false)
{
Application.Run(new Form1());
}
else {
Application.Exit();
}
//===========
//Application.Run(new Form1());
}
}
}