C# 只允许开启一个exe程序

C# 只允许开启一个exe程序

第一种方法

电脑只能启动一次再次点击显示当前exe程序

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BulletinBoard
{
    static class Program
    {
        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern int SetForegroundWindow(IntPtr hwnd);
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x112;
        public const int SC_RESTORE = 0xF120;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
             Process cur = Process.GetCurrentProcess();
             foreach (Process p in Process.GetProcesses())
             {
                 if (p.Id == cur.Id) continue;
                 if (p.ProcessName == cur.ProcessName)
                 {
                     SetForegroundWindow(p.MainWindowHandle);
                     SendMessage(p.MainWindowHandle, WM_SYSCOMMAND, SC_RESTORE, 0);
                     return;
                 }
             }
             Application.EnableVisualStyles();
             Application.SetCompatibleTextRenderingDefault(false);
             Application.Run(new Form1());
            
        }
    }
}

第二种方法

电脑只能启动一次再次点击重新启动exe程序

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BulletinBoard
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
        
            Process current = Process.GetCurrentProcess();
    Process[] pp = Process.GetProcessesByName(current.ProcessName);
    foreach(Process p in pp)
    {
        if (p.Id != current.Id)
        {
            if (p.MainModule.FileName == current.MainModule.FileName)
            {
                p.Kill();
                break;
            }
        }
     }
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            
        }
       
    }
}
相关推荐
Wenweno0o7 小时前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
chenjingming6667 小时前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
cch89188 小时前
Python主流框架全解析
开发语言·python
不爱吃炸鸡柳8 小时前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发8 小时前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射
Momentary_SixthSense8 小时前
设计模式之工厂模式
java·开发语言·设计模式
‎ദ്ദിᵔ.˛.ᵔ₎8 小时前
STL 栈 队列
开发语言·c++
勿忘,瞬间8 小时前
数据结构—顺序表
java·开发语言
张張4088 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533998 小时前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python