现在的位置: 首页 > 综合 > 正文

c# 更改注册表开机启动+mutex(互斥,同一时间同一台电脑只能运行一个程序)

2013年10月23日 ⁄ 综合 ⁄ 共 8085字 ⁄ 字号 评论关闭

1.更改注册表,使开机启动

在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run下增加一个键,键值为程序路径即可,代码如下:

    string strName = Application.ExecutablePath;
            string strnewName = strName.Substring(strName.LastIndexOf("\\") + 1);
            if (!checkBox_start.Checked)
            {
                //修改注册表,使程序开机时不自动执行。  
                Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                Rkey.DeleteValue(strnewName, false);
                MessageBox.Show("程序设置完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                if (!File.Exists(strName))//指定文件是否存在  
                    return;
                Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (Rkey == null)
                    Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                Rkey.SetValue(strnewName, strName);//修改注册表,使程序开机时自动执行。 
                MessageBox.Show("程序设置完成,重新启动计算机后即可生效!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

2.通过使用mutex(互斥),确保当前电脑里只有一个该程序在运行(需引用命名空间:using System.Threading;,或者代替mutex为System.Threading.Mutex):

 互斥进程(程序), 简单点说,就是在系统中只能有该程序的一个实例运行 要实现程序的互斥,通常有三中方式,下面用 C#  语言来实现:

实现方式一: 使用线程互斥变量. 通过定义互斥变量来判断是否已运行实例.C#实现如下:

    把program.cs文件里的Main()函数改为如下代码:

        static void Main()
        {
            bool runone;
            Mutex run = new Mutex(true, @"Global\TaskPublish", out  runone);
            if (runone)
            {
              run.ReleaseMutex();
              Application.EnableVisualStyles();
              Application.SetCompatibleTextRenderingDefault(false);
              Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已经运行了一个实例了。");
            }
        }

  说明:程序中通过语句 System.Threading.Mutex run = new System.Threading.Mutex(true, "xinbiao_a_test", out runone);来申明一个互斥体变量run,其中"xinbiao_a_test"为互斥体名,布尔变量runone用来保存是否已经运行了该程序事例.

实现方式二:   采用判断进程的方式,我们在运行程序前,查找进程中是否有同名的进程,同时运行位置也相同程,如是没有运行该程序,如果有就就不运行.在C#中应用System.Diagnostics名字空间中的Process类来实现,主要代码如下:

        1,在program.cs文件中添加函数如下:

        public static System.Diagnostics.Process RunningInstance() 
        {
            System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess();
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process process in processes) //查找相同名称的进程
            {
                if (process.Id != current.Id)  //忽略当前进程
                { //确认相同进程的程序运行位置是否一样. 
                    if (System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", @"\") == current.MainModule.FileName) 
                    { //Return the other process instance.                       
                        return process;
                    } 
                } 
            } //No other instance was found, return null. 
            return null; 
        }  

        2,把Main ()函数改为如下代码:

        static void Main()
        {
            if(RunningInstance()==null)
            { 
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已经运行了一个实例了。");
            }
        }

实现方式三:全局原子法,创建程序前,先检查全局原子表中看是否存在特定原子A(创建时添加的),存在时停止创建,说明该程序已运行了一个实例;不存在则运行程序并想全局原子表中添加特定原子A;退出程序时要记得释放特定的原子A哦,不然要到关机才会释放。C#实现如下:

1、申明WinAPI函数接口:

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalAddAtom(String lpString);  //添加原子

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalFindAtom(String lpString);  //查找原子

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom);  //删除原子

2、修改Main()函数如下:

        static void Main()
        {
            if (GlobalFindAtom("xinbiao_test") == 77856768) //没找到原子"xinbiao_test"
            {
                GlobalAddAtom("xinbiao_test");  //添加原子"xinbiao_test"
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已经运行了一个实例了。");
            }                        
        }

3、在FormClosed事件中添加如下代码:

       GlobalDeleteAtom(GlobalFindAtom("xinbiao_test"));//删除原子"xinbiao_test"

以上为创建互斥程序(进程)的基本通用的思想,个人认为,第一种方法最好。以上所有代码都在VS.NET2005 中测试通过。

互斥进程(程序), 简单点说,就是在系统中只能有该程序的一个实例运行. 现在很多软件都有这功能,如Maxthon 可以设置为"只允许打开一个窗体",还有Bitcomet等. 我也是看到这些软件的这个功能才来研究这个问题的.  要实现程序的互斥,通常有三中方式,下面用 C#  语言来实现:

实现方式一: 使用线程互斥变量. 通过定义互斥变量来判断是否已运行实例.C#实现如下:

    把program.cs文件里的Main()函数改为如下代码:

        static void Main()
        {
            bool runone;
            System.Threading.Mutex run = new System.Threading.Mutex(true, "xinbiao_a_test", out runone);
            if (runone)
            {
              run.ReleaseMutex();
              Application.EnableVisualStyles();
              Application.SetCompatibleTextRenderingDefault(false);
              Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已经运行了一个实例了。");
            }
        }

  说明:程序中通过语句 System.Threading.Mutex run = new System.Threading.Mutex(true, "xinbiao_a_test", out runone);来申明一个互斥体变量run,其中"xinbiao_a_test"为互斥体名,布尔变量runone用来保存是否已经运行了该程序事例.

实现方式二:   采用判断进程的方式,我们在运行程序前,查找进程中是否有同名的进程,同时运行位置也相同程,如是没有运行该程序,如果有就就不运行.在C#中应用System.Diagnostics名字空间中的Process类来实现,主要代码如下:

        1,在program.cs文件中添加函数如下:

        public static System.Diagnostics.Process RunningInstance() 
        {
            System.Diagnostics.Process current = System.Diagnostics.Process.GetCurrentProcess();
            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process process in processes) //查找相同名称的进程
            {
                if (process.Id != current.Id)  //忽略当前进程
                { //确认相同进程的程序运行位置是否一样. 
                    if (System.Reflection.Assembly.GetExecutingAssembly().Location.Replace("/", @"\") == current.MainModule.FileName) 
                    { //Return the other process instance.                       
                        return process;
                    } 
                } 
            } //No other instance was found, return null. 
            return null; 
        }  

        2,把Main ()函数改为如下代码:

        static void Main()
        {
            if(RunningInstance()==null)
            { 
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已经运行了一个实例了。");
            }
        }

实现方式三:全局原子法,创建程序前,先检查全局原子表中看是否存在特定原子A(创建时添加的),存在时停止创建,说明该程序已运行了一个实例;不存在则运行程序并想全局原子表中添加特定原子A;退出程序时要记得释放特定的原子A哦,不然要到关机才会释放。C#实现如下:

1、申明WinAPI函数接口:

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalAddAtom(String lpString);  //添加原子

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalFindAtom(String lpString);  //查找原子

        [System.Runtime.InteropServices.DllImport("kernel32.dll")]

        public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom);  //删除原子

2、修改Main()函数如下:

        static void Main()
        {
            if (GlobalFindAtom("xinbiao_test") == 77856768) //没找到原子"xinbiao_test"
            {
                GlobalAddAtom("xinbiao_test");  //添加原子"xinbiao_test"
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                MessageBox.Show("已经运行了一个实例了。");
            }                        
        }

3、在FormClosed事件中添加如下代码:

       GlobalDeleteAtom(GlobalFindAtom("xinbiao_test"));//删除原子"xinbiao_test"

以上为创建互斥程序(进程)的基本通用的思想,个人认为,第一种方法最好。

抱歉!评论已关闭.