C# winform程序实现开机自启动,而且识别是开机启动仍是双击启动

开机启动程序,在不少场合都会用到,尤为是那种在后台运行的程序。api

效果图:数组

 

 

以上两幅图都用到了命令行启动程序,为了模拟开机启动或者其余程序调用此程序。ide

第一幅图:程序启动能够根据不一样参数,执行不一样的操做。若是是双击启动,就自动运行逻辑代码,若是是带特定参数启动,就自动运行逻辑代码。函数

第二幅图:winform 程序设置开机启动,模拟双击启动和开机启动的不一样效果。ui

 

开机启动并自动运行方法:其实思路很简单,就是将程序添加到注册表中,这设置值的时候,加一个参数就能够了。而后程序在入口函数处判断启动参数,若是有启动参数,就走自动运行逻辑代码,若是没有,就只是程序启动,并不运行逻辑代码。this

 

【Main参数】

   在C/C++中,咱们很明确的知道 main(int argc, char *argv[]/*, char *envp[]*/) 函数有两(三)个参数,第三个参数通常用得少,我是还没用到过。因此常见的都是用两个参数。第一个是参数个数,非负数。第二个是表示从执行环境传递给程序的各个实参。也就是说,咱们要用程序入口参数,只须要判断argc的值,而后使用数组取argv的值就行。spa

  那么到了C#就变的更简单了。直接变成 string[] 了。那么你只要遍历这个字符串数组就能够了。.net

  咱们用VS建立命令行工程的时候,若是是命令行程序那么VS会默认使用带参数的main函数:void Main(string [] args);若是是winform工程,VS是默认使用void Main()。其实不管默认使用哪一个都无所谓,主要是本身要清楚main函数的格式,以及表明的含义。main函数不光有参数,还能够有返回值。其实咱们平时写的C#工程中main函数看似没有返回值,实际上是能够带有int类型的返回值的。若是你不清楚这一块,传送门命令行

  那若是咱们用的是 void Main() 这种形式咱们怎么获取程序入库参数?这里实际上是只是一个表面现象。别觉得你不带参数,我就获取不到了 ^_^ 。微软为咱们提供了一个类:Environment。这个类比较强大。若是你还不清楚怎么用,那去 MSDN 搜一下就会了。获取命令行参数也就一个函数而已: string[] Environment.GetCommandLineArgs();使用这个方法须要注意就是返回值是数组类型,第一个元素包含正在执行的程序的文件名,从第二个参数开始,才是命令行参数。其实这个办法就恰好解决了 winform 程序中获取命令行参数的问题。code

【注册表操做】

将程序启动写入注册表实现开机启动,这个感受没什么好说的。使用固定方法操做就行。不过用有一点须要注意就是在访问注册表的时候可能会提示没有权限,你这个网上百度有好多方法。可是MSDN中也给出了方法。就是在工程的中添加应用程序文件清单中修改一句就能够了。

 

核心代码:

using System;
using Microsoft.Win32;

namespace AutoStartRun
{
    public sealed class SystemHelper
    {
        private SystemHelper() { }

        /// <summary>
        /// 设置程序开机启动
        /// </summary>
        /// <param name="strAppPath">应用程序exe所在文件夹</param>
        /// <param name="strAppName">应用程序exe名称</param>
        /// <param name="bIsAutoRun">自动运行状态</param>
        public static void SetAutoRun(string strAppPath, string strAppName, bool bIsAutoRun)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(strAppPath)
                    || string.IsNullOrWhiteSpace(strAppName))
                {
                    throw new Exception("应用程序路径或名称为空!");
                }

                RegistryKey reg = Registry.LocalMachine;
                RegistryKey run = reg.CreateSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");

                if (bIsAutoRun)
                {
                    run.SetValue(strAppName, strAppPath);
                }
                else
                {
                    if (null != run.GetValue(strAppName))
                    {
                        run.DeleteValue(strAppName);
                    }
                }

                run.Close();
                reg.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        /// <summary>
        /// 判断是否开机启动
        /// </summary>
        /// <param name="strAppPath">应用程序路径</param>
        /// <param name="strAppName">应用程序名称</param>
        /// <returns></returns>
        public static bool IsAutoRun(string strAppPath, string strAppName)
        {
            try
            {
                RegistryKey reg = Registry.LocalMachine;
                RegistryKey software = reg.OpenSubKey(@"SOFTWARE");
                RegistryKey run = reg.OpenSubKey(@"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\");
                object key = run.GetValue(strAppName);
                software.Close();
                run.Close();
                if (null == key || !strAppPath.Equals(key.ToString()))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
    }
}

 调用方法:

        /// <summary>
        /// 设置程序开机自启动
        /// </summary>
        private void SetAutoRun()
        {
            string strFilePath = Application.ExecutablePath;
            string strFileName = System.IO.Path.GetFileName(strFilePath);

            try
            {
                SystemHelper.SetAutoRun(strFilePath + " -autostart", strFileName, !menuAutoRun.Checked);
                menuAutoRun.Checked = !menuAutoRun.Checked;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }        

设置开机启动就是如此简单。

【开机启动并运行】

 那这个就不用说了,将命令行参数和开机注册表操做结合起来就能够了。

示例代码:

        /// <summary>
        /// 检查是否开机启动,并设置控件状态
        /// </summary>
        private void CheckAutoRun()
        { 
            string strFilePath = Application.ExecutablePath;
            string strFileName = System.IO.Path.GetFileName(strFilePath);

            if (SystemHelper.IsAutoRun(strFilePath + " -autostart", strFileName))
            {
                menuAutoRun.Checked = true;
            }
            else
            {
                menuAutoRun.Checked = false;
            }
        }

        private void AutoRun()
        {
            if (menuAutoRun.Checked)
            {
                string[] strArgs = Environment.GetCommandLineArgs();
                if (strArgs.Length >= 2 && strArgs[1].Equals("-autorun"))
                {
                    labText.Text = "我是开机自启动运行...";
                }
            }
        }

 

 献上 demo

相关文章
相关标签/搜索