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)  編輯  收藏


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


          網站導航:
           
          主站蜘蛛池模板: 汉源县| 绵阳市| 昌黎县| 金溪县| 深州市| 永川市| 青岛市| 临夏县| 曲阳县| 安阳市| 华阴市| 阳城县| 闵行区| 平塘县| 永寿县| 平昌县| 淮阳县| 天长市| 龙岩市| 元氏县| 澄城县| 安仁县| 新津县| 敖汉旗| 汉中市| 浏阳市| 潜山县| 澎湖县| 双流县| 鄂尔多斯市| 新巴尔虎右旗| 宣化县| 济源市| 大埔区| 阳信县| 子长县| 繁峙县| 崇义县| 中牟县| 蓬莱市| 兴国县|