ibcadmin 发表于 2013-1-15 18:37:14

C#实现开机自动启动(关联注册表)



当我们做一个程序出来,需要程序开机时候自动运行,那我们该怎么办?

实现开机启动,当然离不开注册表了。

那么在C#中我们如何操作注册表,实现开机自动启动呢?


有两种方法:

第一种方法:

1.引用命名空间


using Microsoft.Win32;

2.在你的触发事件中写如下代码,拿load事件作例子:

   //获取程序执行路径..
    string starupPath = Application.ExecutablePath;
    //class Micosoft.Win32.RegistryKey. 表示Window注册表中项级节点,此类是注册表装.
    RegistryKey loca = Registry.LocalMachine;
    RegistryKey run = loca.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
   
    try
    {
      //SetValue:存储值的名称
run.SetValue("WinForm",starupPath);
MessageBox.Show(" 注册表添加成功!!",""提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
      loca.Close();
    }
    catch(Exception ee)
    {
      MessageBox.Show(ee.Message.ToString(),"提 示",MessageBoxButtons.OK,MessageBoxIcon.Error);
    }



第二种方法:

添加到注册表里直接用代码写到注册表里,也可以手动添加.

E:D:\\tractor.exe//可以是你的程序名和 完整路径就OK了.

也可以手动拖到启动里面....


RegistryKey hklm = Application.LocalMachine;
RegistryKey run = hklm.CreateSubKey(@"SOFTWARE\Microsoft\Windows\Current\Version\Run");
try
{
    run.SetValue("tractor.exe","D:\\tractor.exe");
    MessageBox.Show("注册表添加成功!!","提示",MessageBoxButton.OK, MessageBoxIcon.Information);
    hklm.Close();
}

catch(Exception ee)
{
    MessageBox.Show(my.Message.ToString(),"提示",MessageBoxButton.OK, MessageBoxIcon.Error);
}



有问题 楼下问。

chao2332601 发表于 2013-6-16 02:01:10

谢谢分享!!!

chao2332601 发表于 2013-6-16 05:02:03

谢谢分享!!!
页: [1]
查看完整版本: C#实现开机自动启动(关联注册表)