zl程序教程

您现在的位置是:首页 >  后端

当前栏目

让C#程序只运行一个实例,显示已经运行的界面

c#实例程序 一个 运行 显示 界面 已经
2023-09-27 14:28:14 时间

            bool isNew;

            mutex = new System.Threading.Mutex(true, "myproject", out isNew);

            if (isNew)

            {

                Application.EnableVisualStyles();

                Application.SetCompatibleTextRenderingDefault(false);

                Application.Run(new Login());

            }

            else

            {

                MessageBox.Show("本程序已经在运行!","提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning);

            }

        }

 

让程序只运行一个实例的方法二(会显示正在运行的窗口): static void Main()

        {

            Process instance = RunningInstance();

            if (instance == null)

            {

                Application.EnableVisualStyles();

                Application.SetCompatibleTextRenderingDefault(false);

                Application.Run(new Login());

            }

            else

            {

                HandleRunningInstance(instance);

            }

 

        }

 

//返回正在运行的程序进程

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;//第一次运行,返回null

        }

//显示正在运行的进程当前窗口

public static void HandleRunningInstance(Process instance)

        {

            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL); //置窗口为正常状态

            SetForegroundWindow(instance.MainWindowHandle);

        }

 

        #region调用系统api

        [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;

        #endregion


当双击某程序到它显示运行界面时,操作系统都做了啥? 假设:我们现在想要让操作系统运行「微信」,那么首先我们会怎么做嘞?在整个过程中,操作系统又做了啥? 如果这是一个面试题,你会怎么回答呢?来看看阿粉的解释~