【程式篇】防止程式多開的兩種方法
<a target=_blank href="http://bbs.cskin.net/forum.php?mod=viewthread&tid=105&fromuid=2446" target="_blank" rel="external nofollow" >http://bbs.cskin.net/forum.php?mod=viewthread&tid=105&fromuid=2446</a>
(出處: CSkin論壇)
互斥對象防止程式多開
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();//關閉目前窗體
}