喜气羊羊

羊羊其实是条鱼|每天学习一点点|每天进步一点点

  PHP博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  68 随笔 :: 0 文章 :: 63 评论 :: 0 Trackbacks
Mutex翻译过来就是 互斥体

http://dict.iciba.com/mutex/

详见MSDN关于Mutex类的详解

我们现在要实现一个程序只运行一个实例啦

首先创建一个标准的c#窗体程序,打开 Program.cs
我们可以看到自动生成的代码如下:


using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace MutexForm
{
    
static class Program
    {
        
/// <summary>
        
/// The main entry point for the application.
        
/// </summary>
        [STAThread]
        
static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(
false);
            Application.Run(
new Form1());           
        }
    }
}


我们将代码做一点修改:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;

namespace MutexForm
{
    
static class Program
    {
        
/// <summary>
        
/// The main entry point for the application.
        
/// </summary>
        [STAThread]
        
static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(
false);

            
//只运行一个实例
            bool createNew;
            Mutex m 
= new Mutex(true"MutexForm"out createNew);
            
if (createNew)
            {
                Application.Run(
new Form1());
                m.ReleaseMutex();
            }
        }
    }
}

Ok啦,运行一下,可以看到我们的程序只会运行一个实例啦

PS:代码很简单,但是美中不足,似乎不能第二次运行的时候,激活前一个实例
如果可以激活前一个实例就好了
希望达人赐教哈。。

posted on 2008-08-17 22:33 young40 阅读(956) 评论(0)  编辑 收藏 引用 网摘 所属分类: .Net[C#]

只有注册用户登录后才能发表评论。
网站导航: