同一个应用程序只开启一个的方法

来源:互联网 发布:卖家加入农村淘宝 编辑:程序博客网 时间:2024/04/28 14:55

引子:平时我们用的很多软件,如很多的播放器,酷我音乐盒等都只能打开一个,如果你再点击快捷方式,它会把你之前打开的

            界面重新打开,本篇文章就是介绍它的实现方法。 

在讲解它的实现之前先来看里面的一个关键点---------密封类Mutex:

         在MSDN(点击打开(Mutex类)链接)中是这样解释的:一个同步基元,也可用于进程间同步。 其实个人感觉更容易理解的解释是:

互斥锁(Mutex)

互斥锁是一个互斥的同步对象,意味着同一时间有且仅有一个线程可以获取它。

互斥锁可适用于一个共享资源每次只能被一个线程访问的情况。

如果要获取一个互斥锁。应调用互斥锁上的WaitOne()方法,该方法继承于Thread.WaitHandle类。

它处于等到状态直至所调用互斥锁可以被获取,因此该方法将组织住主调线程直到指定的互斥锁可用,如果不需要拥有互斥锁,用ReleaseMutex方法释放,从而使互斥锁可以被另外一个线程所获取。

这是我改自MSDN上的方法(其实也没有该多少):

using System;using System.Threading;class Test{    // Create a new Mutex. The creating thread does not own the    // Mutex.    private static Mutex mut = new Mutex();    static void Main()    {        // Create the threads that will use the protected resource.        for(int i = 0; i < 5; i++)        {            Thread myThread = new Thread(new ThreadStart(MyThreadProc));            myThread.Name = String.Format("Thread{0}", i + 1);            myThread.Start();        }        // The main thread exits, but the application continues to        // run until all foreground threads have exited.    }    private static void MyThreadProc()    {          UseResource();    }    // This method represents a resource that must be synchronized    // so that only one thread at a time can enter.    private static void UseResource()    {        // Wait until it is safe to enter.        mut.WaitOne();        Console.WriteLine("{0} has entered the protected area",             Thread.CurrentThread.Name);        // Place code to access non-reentrant resources here.        // Simulate some work.        Thread.Sleep(500);        Console.WriteLine("{0} is leaving the protected area\r\n",             Thread.CurrentThread.Name);                 // Release the Mutex.        mut.ReleaseMutex();    }}

其实说白了就是:这个坑儿(Mutex mutex)谁蹲下,别个就只能等(mutex.WaitOne();),只有等蹲坑那个人爽完了(mutex.ReleaseMutex();),等待的那个人才能去蹲,然后再让另外的人去等待....

 

好,现在来说下关键的东西:

首先在你的项目的Program文件里面,添加如下代码:

 

        [STAThread]        static void Main()//Main方法        {            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);               bool flag = false;            mutexCurrentApp = new Mutex(true, Application.ProductName, out flag);   //第一个参数:true--给调用线程赋予互斥体的初始所属权              //第一个参数:互斥体的名称              //第三个参数:返回值,如果调用线程已被授予互斥体的初始所属权,则返回true
   if (!flag)            {                Process instance = GetExistProcesses();                if (instance != null)                {                    SetForeground(instance);                    return;                }            }            Application.Run(new SysForm2());        }        //引用一个Win32API函数        [DllImport("user32.dll")]        public static extern bool SetForegroundWindow(IntPtr hwnd);        private static void SetForeground(Process instance)        {            IntPtr mainFormHandle = instance.MainWindowHandle;            if (mainFormHandle != IntPtr.Zero)            {                SetForegroundWindow(mainFormHandle);            }        }        private static Process GetExistProcesses()        {            Process currentProcess = Process.GetCurrentProcess();            foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))            {                if (process.Id != currentProcess.Id && IsTheSameMainModule(currentProcess, process))                {                    return process;                }            }            return null;        }        private static bool IsTheSameMainModule(Process currentProcess, Process process)        {            try            {                return string.Equals(currentProcess.MainModule.ModuleName, process.MainModule.ModuleName);            }            catch            {            }            return true;        }

整段代码的意思就是:如果你已经打开当前的应用程序,但是你还去点击打开应用程序,它不会重新打开一个,只会把已经打开的放在桌面的最前端。

 

原创粉丝点击