C#运行程序始终保持只可以打开一个

方法一:如果程序已经在运行,则直接将运行的程序显示出来

//引入3个命名空间

using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;

namespace MyWindow
{
    static class Program
    {
        [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;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Process instance = RunningInstance();
            if (instance == null)
            {
                Form1 frm = new Form1();
                Application.Run(new Form1());
            }
            else
            {
                HandleRunningInstance(instance);
            }
        }

        /// <summary>
        /// 获取正在运行的实例,没有运行的实例返回null;
        /// </summary>
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// 显示已运行的程序。
        /// </summary>
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //显示,可以注释掉
            SetForegroundWindow(instance.MainWindowHandle);            //放到前端
        }
    }
}

方法二:如果程序已经在运行,只提示“有程序运行”
            System.Threading.Mutex mutex;
            bool isNew;
            mutex = new System.Threading.Mutex(true, "myproject", out isNew);
            if (isNew)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("本程序已经在运行");
            }

猜你喜欢

转载自blog.csdn.net/Hat_man_/article/details/115084923