1. 程式人生 > >C# 防止程序多開的兩種方法

C# 防止程序多開的兩種方法

獲取 message 進程資源 信息 lse 多次 ase send true

互斥對象防止程序多開


private void Form1_Load(object sender, EventArgs e)
{
    bool Exist;//定義一個bool變量,用來表示是否已經運行
    //創建Mutex互斥對象
    System.Threading.Mutex newMutex = new System.Threading.Mutex(true, "僅一次", out Exist);
    if (Exist)//如果沒有運行
    {
        newMutex.ReleaseMutex();//運行新窗體
    }
    else
    {
        MessageBox.Show("本程序一次只能運行一個實例!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);//彈出提示信息
        this.Close();//關閉當前窗體
    }
}

進程檢查


private void Form1_Load(object sender, EventArgs e)
{
    //獲取當前活動進程的模塊名稱
    string moduleName = Process.GetCurrentProcess().MainModule.ModuleName;
    //返回指定路徑字符串的文件名
    string processName = System.IO.Path.GetFileNameWithoutExtension(moduleName);
    //根據文件名創建進程資源數組
    Process[] processes = Process.GetProcessesByName(processName);
    //如果該數組長度大於1,說明多次運行
    if (processes.Length > 1)
    {
        MessageBox.Show("本程序一次只能運行一個實例!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);//彈出提示信息
        this.Close();//關閉當前窗體
    }

  轉至: https://www.test404.com/post-713.html?wafcloud=1

C# 防止程序多開的兩種方法