tbwshc

          如何使自己的程序只運行一次

          我介紹兩個主流的方法。

          方法一:使用Mutex來進行

          1. 首先要添加如下的namespace:

          using System.Threading;


          2. 修改系統Main函數,大致如下:

          bool bCreatedNew;

          //Create a new mutex using specific mutex name
          Mutex m =new Mutex( false, "myUniqueName", out bCreatedNew );
          if( bCreatedNew )
          Application.Run(new yourFormName());

          如上面編碼就可以了,要注意的一點是,在給Mutex起名字的時候,不要太簡單,以tb防止和其他程序的Mutex重復,從而達不到所預想的效果。


          方法二:使用Process來進行

          1. 首先要添加如下的namespace:

          using System.Diagnostics;
          using System.Reflection;

          2. 添加如下函數:

          public static Process RunningInstance()
          {
          Process current = Process.GetCurrentProcess();
          Process[] processes = Process.GetProcessesByName(current.ProcessName);

          //Loop through the running processes in with the same name
          foreach (Process process in processes)
          {
          //Ignore the current process
          if (process.Id != current.Id)
          {
          //Make sure that the process is running from the exe file.
          if (Assembly.GetExecutingAssembly().Location.Replace("/", "http://") == current.MainModule.FileName)
          {
          //Return the other process instance.
          return process;
          }
          }
          }

          //No other instance was found, return null.
          return null;
          }

          3. 修改系統Main函數,大致如下:

          if( RunningInstance() == null )
          Application.Run(new yourFormName());

          如上面編碼就可以了,要注意的一點是,在判斷進程模塊文件名是否相等這部分的代碼,是可選的。如果當前的程序在文件系統中只存在一個的話,以上的方法是可以的;否則不要刪除這部分的代碼。


          對比兩種方法,就效率和簡便性來說,前一種方法是最好的,也是我比較喜歡的;后一種方法,速度比較慢,其次通過ProcessName去系統中查尋,有可能查出來的Process并不是我想要得,雖說在后面加了文件目錄判斷,但是其含有潛在的問題(前面已經說出來)。不過,第一種方法也有缺陷,就是擴展性操作不方便,例如:讓程序只運行一次,如果程序已經運行,把它彈出并顯示到最前面。對于此,后一種方法就很有優勢了。

           

          posted on 2012-07-05 13:25 chen11-1 閱讀(770) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 临桂县| 开原市| 行唐县| 井冈山市| 景洪市| 从化市| 侯马市| 江山市| 句容市| 东兴市| 家居| 定结县| 应用必备| 密云县| 天柱县| 定日县| 丘北县| 永仁县| 双牌县| 内乡县| 厦门市| 讷河市| 张家口市| 昌吉市| 墨玉县| 松溪县| 黄平县| 子洲县| 同江市| 岑巩县| 河间市| 伊川县| 鹤庆县| 滦南县| 连江县| 乐平市| 湘阴县| 桂林市| 资源县| 上林县| 平原县|