使自己的程式只運行一次

來源:互聯網
上載者:User

我介紹兩個主流的方法。

方法一:使用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起名字的時候,不要太簡單,以防止和其他程式的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("/", "\\") == 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並不是我想要得,雖說在後面加了檔案目錄判斷,但是其含有潛在的問題(前面已經說出來)。不過,第一種方法也有缺陷,就是擴充性操作不方便,例如:讓程式只運行一次,如果程式已經運行,把它彈出並顯示到最前面。對於此,後一種方法就很有優勢了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.