使用一個具名的Mutex(Mutex的名字是整個作業系統共享的)控管,先用OpenExisting方法尋找目前存不存在,若不存在則新增若新增時發現已經新增過了就結束程式,程式碼如下所示:



using System.Threading;

using System.Security.AccessControl;




private void WindowLoaded(object sender, RoutedEventArgs e)

        {

            System.Console.WriteLine("windnowloaded");


            bool mutexIsNew = false;

           


            try

            {

                // Open the mutex with (MutexRights.Synchronize |

                // MutexRights.Modify), to enter and release the

                // named mutex.

                //


                m = Mutex.OpenExisting(mutexName);

            }

            catch (WaitHandleCannotBeOpenedException)

            {

                Console.WriteLine("Mutex does not exist.");

                mutexIsNew = true;

            }

            catch (UnauthorizedAccessException ex)

            {

                Console.WriteLine("Unauthorized access: {0}", ex.Message);

              

                Window.Close();

            }


            if (mutexIsNew)

            {


                //run

                System.Console.WriteLine("mutexIsNew:" + mutexIsNew);

                MutexSecurity mSec = new MutexSecurity();


                m = new Mutex(true, mutexName, out mutexWasCreated, mSec);


                // If the named system mutex was created, it can be

                // used by the current instance of this program, even

                // though the current user is denied access. The current

                // program owns the mutex. Otherwise, exit the program.

                //


                if (mutexWasCreated)

                {

                    Console.WriteLine("Created the mutex.");

                  

                }

               

            }

            else

            {

                //close

                Window.Close();

            }

}

狼翔月影 發表在 痞客邦 PIXNET 留言(0) 人氣()