2013年12月24日 星期二

C# 防止重複執行程式

http://tw.myblog.yahoo.com/jw!TH0Xl0OBGBYtk2mBhmZRIFJKSl4-/article?mid=700

http://lopechu6.blogspot.tw/2013/02/c.html


很多程式為常駐的程式,為了防止重複執行造成的怪怪結果
可用此方式偵測是否已經執行
 1. 宣告bool變數來接收結果 範例內為宣告 bool isAppRunning = false;
 2. 加上 System.Threading.Mutex mutex = new System.Threading.Mutex(true, System.Diagnostics.Process.GetCurrentProcess().ProcessName, out isAppRunning);
 3. 判斷回傳結果 isAppRunning = false; //代表執行中
                              isAppRunning = true;   //尚未執行
PS:此方法有各缺點,如果同一個程式但在不同目錄時還是可以重複執行
[STAThread]
static void Main()
{
    bool isAppRunning = false;
    System.Threading.Mutex mutex = new System.Threading.Mutex(
        true,
        System.Diagnostics.Process.GetCurrentProcess().ProcessName,
        out isAppRunning);
    if (!isAppRunning)
    {
        MessageBox.Show("程式執行中!");
        Environment.Exit(1);
    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}



==================================



using System.Diagnostics;
...
...
//=====不可重複開啟同一支程式(將程式碼放至於偵測是否被開啟的程式中即可)=====
Process[] proc = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);
if (proc.Length > 1)
{
    //表示此程式已被開啟
    MessageBox.Show("程式執行中");
}

//=====偵測執行中的外部程式並關閉=====
Process[] MyProcess = Process.GetProcessesByName("程式名稱");
if (MyProcess.Length>0)
    MyProcess[0].Kill(); //關閉執行中的程式
 

MangoHost Copyright © 2009 Cookiez is Designed by Ipietoon for Free Blogger Template