怪奇物语

怪奇物语

首页 新随笔 联系 管理

C# winform WPF 防止应用重复打开

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;

static class Program
{
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main()
    {
        👇👇👇👇👇👇👇👇👇👇👇👇👇👇
        Process instance = RunningInstance();
        if (instance != null)
        {
            MessageBox.Show("程序运行中,请勿重复打开!", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            👇👇👇👇👇👇👇👇👇👇👇👇👇👇
            HandleRunningInstance(instance);
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

    public static Process RunningInstance()
    {
        Process currentprocess = Process.GetCurrentProcess();
        Process[] processes = Process.GetProcessesByName(currentprocess.ProcessName);
        foreach (Process process in processes)
        {
            if (process.Id != currentprocess.Id)
            {
                return process;
            }
        }
        return null;
    }

    private static void HandleRunningInstance(Process instance)
    {
        ShowWindowAsync(instance.MainWindowHandle, SW_SHOWNOMAL);
        SetForegroundWindow(instance.MainWindowHandle);
    }

    [DllImport("User32.DLL")]
    private static extern bool ShowWindowAsync(IntPtr hwnd, int cmdShow);

    private const int SW_SHOWNOMAL = 1;

    [DllImport("User32.DLL")]
    private static extern bool SetForegroundWindow(IntPtr hwnd);
}



posted on 2025-07-02 08:00  超级无敌美少男战士  阅读(42)  评论(0)    收藏  举报