您可以使用线程互斥锁和 user32.dll
尝试这个
第 1 步:声明以下常量:
private const int SW_NORMAL = 1; // see WinUser.h for definitions
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_RESTORE = 9;
[DllImport("User32", EntryPoint = "FindWindow")]
static extern IntPtr FindWindow(string className, string windowName);
[DllImport("User32", EntryPoint = "SendMessage")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32", EntryPoint = "SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("User32", EntryPoint = "SetWindowPlacement")]
private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("User32", EntryPoint = "GetWindowPlacement")]
private static extern bool GetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
private struct WINDOWPLACEMENT
{
public int length;
public int flags;
public int showCmd;
}
第 2 步:添加此方法:
public void application_run(Form form1)
{
bool createdNew;
System.Threading.Mutex m = new System.Threading.Mutex(true, form1.Name, out createdNew);
if (!createdNew)
{
MessageBox.Show("...", "...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);//Alert message
try
{
// see if we can find the other app and Bring it to front
IntPtr hWnd = FindWindow(null, form1.Text);
if (hWnd != IntPtr.Zero)
{
LoaderDomain.WINDOWPLACEMENT placement = new LoaderDomain.WINDOWPLACEMENT();
placement.length = Marshal.SizeOf(placement);
GetWindowPlacement(hWnd, ref placement);
placement.showCmd = SW_SHOWMAXIMIZED;
SetWindowPlacement(hWnd, ref placement);
SetForegroundWindow(hWnd);
}
}
catch
{
//rien
}
}
else
{
Application.Run(form1);
}
// keep the mutex reference alive until the normal termination of the program
GC.KeepAlive(m);
}
第 3 步:在主目录中替换
Application.run(forms);
通过调用之前的方法