C#實現自動啟動

来源:互联网 发布:python 小程序 编辑:程序博客网 时间:2024/06/08 08:19
private void toolStripMenuItem3_Click(object sender, EventArgs e)
        
{
            
if (autorun == true)
            
{
                RunWhenStart(
false, Application.ProductName, Application.StartupPath + @"" + Application.ProductName+@".exe");
                autorun 
= false;
            }

            
else
            
{
                RunWhenStart(
true, Application.ProductName, Application.StartupPath + @"" + Application.ProductName + @".exe");
                autorun 
= true;
            }

            Config a 
= new Config();
            a.WriteConfig(
"autorun", autorun.ToString());
            toolStripMenuItem3.Checked 
= autorun;
        }


        
public static void RunWhenStart(bool Started, string name, string path)
        
{
            RegistryKey HKLM 
= Registry.LocalMachine;
            RegistryKey Run 
= HKLM.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
            
if (Started == true)
            
{
                
try
                
{
                    Run.SetValue(name, path);
                    HKLM.Close();
                }

                
catch (Exception Err)
                
{
                    MessageBox.Show(Err.Message.ToString(), 
"友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

            
else
            
{
                
try
                
{
                    Run.DeleteValue(name);
                    HKLM.Close();
                }

                
catch (Exception)
                
{
                    MessageBox.Show(Err.Message.ToString(), 
"友情提醒", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

        }
 
 
原创粉丝点击