0
点赞
收藏
分享

微信扫一扫

C#编写的windows程序随系统启动的问题

 

C#写了一个windows的程序,想让它随系统启动运行

--------------

把可执行文件的快捷方式复制到启动文件夹里面,这样不安全,安全的方法是把系统做成WinService的方式,以系统服务的方式安全好多

--------------

设置某程序随系统启动自动运行,取消自动运行。 使用到using Microsoft.Win32;名称空间。

public void SetAutoRun(string fileName, bool isAutoRun)   
        {   
                RegistryKey reg = null;   
                try  
                {   
                    if (!System.IO.File.Exists(fileName))   
                        throw new Exception("该文件不存在!");   
                    String name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);   
                    reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);   
                    if (reg == null)   
                        reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");   
                    if (isAutoRun)   
                        reg.SetValue(name, fileName);   
                    else  
                        reg.SetValue(name, false);     
                    MessageBox.Show("设定成功!","提示");     
                }   
                catch  
                {   
                    //throw new Exception(ex.ToString());   
                }   
                finally  
                {   
                    if (reg != null)   
                        reg.Close();   
                }   
         }

使用此方法可设置某程序自动运行和取消自动运行。fileName:设置(取消)自动运行程序的完整地址,isAutoRun:是否设置自动运行和取消自动运行。true,自动运行。false,取消自动运行。

原理:操作注册表。

--------------

http://www.ziyouxue.net/2009/0804/5970.html




举报

相关推荐

0 条评论