using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
class Program
{
    // 导入user32.dll函数用于窗口操作
    [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)
            {
                // 首次启动 - 正常运行程序
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm()); // 替换为你的主窗体
            }
            else
            {
                // 程序已运行 - 查找并激活现有实例
                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);
                            }
                            // 将窗口带到前台
                            SetForegroundWindow(handle);
                            break;
                        }
                    }
                }
            }
        }
    }
}
// 示例主窗体类(需要根据实际项目替换)
public class MainForm : Form
{
    public MainForm()
    {
        this.Text = "Test Application";
        // 这里添加你的窗体初始化代码
    }
}