using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
class Program
{
// 導(dǎo)入user32.dll函數(shù)用于窗口操作
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
private const int SW_RESTORE = 9; // 還原窗口的命令
static void Main()
{
// 使用唯一的Mutex名稱(建議使用GUID)
bool createdNew;
using (Mutex mutex = new Mutex(true, "Global\\TestAppMutex", out createdNew))
{
if (createdNew)
{
// 首次啟動(dòng) - 正常運(yùn)行程序
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm()); // 替換為你的主窗體
}
else
{
// 程序已運(yùn)行 - 查找并激活現(xiàn)有實(shí)例
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
IntPtr handle = process.MainWindowHandle;
if (handle != IntPtr.Zero)
{
// 如果窗口最小化則還原
if (IsIconic(handle))
{
ShowWindow(handle, SW_RESTORE);
}
// 將窗口帶到前臺(tái)
SetForegroundWindow(handle);
break;
}
}
}
}
}
}
}
// 示例主窗體類(需要根據(jù)實(shí)際項(xiàng)目替換)
public class MainForm : Form
{
public MainForm()
{
this.Text = "Test Application";
// 這里添加你的窗體初始化代碼
}
}?