菜鸟学C#

淡泊以明志,宁静以致远

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1,利用VB的运行时库Microsoft.VisualBasic.dll包含的WindowsFormsApplicationBase类来实现这个功能

2,右键工程-添加引用-选择Microsoft.VisualBasic.dll项。然后添加新类Class1

3,编写代码(Class1.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.ApplicationServices;//注意

namespace WindowsFormsApplication1
{
    class Class1:WindowsFormsApplicationBase
    {
        public Class1()
        {
            this.IsSingleInstance = true; 
        }
        static Class1 app;          //方便客户端程序的编写
        internal static Class1 App  //方便客户端程序的编写
        {
            get
            {
                if (app == null)
                {
                    app = new Class1();
                }
                return app;
            }
        }
        protected override void OnCreateMainForm()//重写主窗体创建函数
        {
            this.MainForm = new Form1();
        }
    }
}

4,改写Program.cs

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

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string [] args)
        {
            Application.EnableVisualStyles();
            //Class1 app = new Class1();//不方便的写法
            //app.Run(args);            //不方便的写法
            Class1.App.Run(args);       //方便写法

            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());
        }
    }
}

5,这样不管运行多少次,它都会限制应用程序只有一个实例。

posted on 2009-07-08 13:13  东东会会  阅读(749)  评论(0)    收藏  举报