using Microsoft.Win32; //操作注冊(cè)表要用的名稱空間
private void button1_Click(object sender, System.EventArgs e) //button1按下后,會(huì)執(zhí)行的方法
{
RegistryKey hklm=Registry.LocalMachine;
RegistryKey run=hklm.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run"); //定義hklm指向注冊(cè)表的LocalMachine,對(duì)注冊(cè)表的結(jié)構(gòu),可以在windows的運(yùn)行里,輸入regedit,運(yùn)行后,可以看看里面的各個(gè)子鍵,其中Software\Microsoft\Windows\CurrentVersion\Run就是關(guān)系到系統(tǒng)中隨系統(tǒng)啟動(dòng)而啟動(dòng)的程序,通稱啟動(dòng)項(xiàng)
try
{
run.SetValue("hello.exe",@"F:\c#\hello\bin\Debug\hello.exe"); //將我們的程序加進(jìn)去,系統(tǒng)啟動(dòng)時(shí),hello.exe就會(huì)隨系統(tǒng)啟動(dòng)而啟動(dòng)了,后面F:\C#....就這個(gè)程序的位置,你可以將hello.exe 換成你自己的,比如:notepad.exe注意修改這個(gè)程序的位置。至于"@"這個(gè)符號(hào)加在"F:\C#\hello\"之前的作用,是為了保證.net編譯器,不將\解釋為轉(zhuǎn)換符,如果這里不用@的話,那就應(yīng)該寫成"F:\\C#\\hello\\",一個(gè)\就要改為兩個(gè)\\。
MessageBox.Show("添加注冊(cè)表啟動(dòng)項(xiàng)成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information); //彈出信息框,提示,已經(jīng)成功添加了。要了解MessageBox.Show的各參數(shù)意義,可以將光標(biāo)放到其里面,按F1,.net的IDE(集成開發(fā)環(huán)境)會(huì)有詳細(xì)的文檔顯示出來,告訴您最權(quán)威詳盡的解釋。
hklm.Close();} //注意,一定要關(guān)閉,注冊(cè)表應(yīng)用。
catch(Exception my) //這是捕獲異常的
{
MessageBox.Show(my.Message.ToString(),"提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, System.EventArgs e) //button1是添加,這個(gè)button2是刪除。后面的實(shí)現(xiàn)都差不多
{
RegistryKey hklm=Registry.LocalMachine;
RegistryKey run=hklm.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
try
{
run.DeleteValue("hello.exe"); //這兒是關(guān)鍵的區(qū)別,刪除hello.exe這個(gè)啟動(dòng)項(xiàng)鍵值
MessageBox.Show("移除注冊(cè)表啟動(dòng)項(xiàng)成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
hklm.Close();
}
catch(Exception my)
{
MessageBox.Show(my.Message.ToString(),"提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
聯(lián)系客服