開機啟動並執行方法我種多樣
這裡介紹一種常見的
採用設定檔方式設定是否開機啟動
1、
設定一個函數檢查一個自啟動鍵是否存在.
private bool IsValueExist(string KeyValue)
{
RegistryKey hklm = Registry.LocalMachine;
RegistryKey run = hklm.CreateSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run");
string ValueStr1 = null;
try
{
ValueStr1 = (string)run.GetValue(KeyValue);
hklm.Close();
}
catch (Exception Er1)
{
MessageBox.Show(Er1.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (ValueStr1 == null)
return false;
else
return true;
}
2、
添加註冊表自啟動鍵的函數SetAutoValue()
private void SetAutoValue(string KeyValue)
{
// 檢查索引值是否已經存在,不會重複註冊
bool RT = this.IsValueExist(KeyValue);
if (RT)
{
// MessageBox.Show( KeyValue + "已經存在,不再建立");
return;
}
RegistryKey hklm = Registry.LocalMachine;
RegistryKey run = hklm.CreateSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run");
try
{
run.SetValue(KeyValue, Application.ExecutablePath); // 獲得路徑和檔案名稱
// MessageBox.Show(" 已經成功設定為自啟動!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
hklm.Close();
}
catch (Exception my)
{
MessageBox.Show(my.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
3、
刪除指定註冊表自啟動鍵函數DelAutoValue()
private void DelAutoValue(string KeyValue)
{
// 檢查索引值是否已經存在,如果已不存在則不操作了
bool RT = this.IsValueExist(KeyValue);
if (!RT)
{
// MessageBox.Show(KeyValue + " 已不存在,無需操作");
return;
}
RegistryKey hklm = Registry.LocalMachine;
RegistryKey run = hklm.CreateSubKey(@"SOFTWARE/Microsoft/Windows/CurrentVersion/Run");
try
{
// run.SetValue(KeyValue, Application.ExecutablePath); // 獲得路徑和檔案名稱
run.DeleteValue(KeyValue);
// MessageBox.Show(" 自啟動已經成功取消!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
hklm.Close();
}
catch (Exception my)
{
MessageBox.Show(my.Message.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
4、
主調函數AutoStartSwitch()
private void AutoStartSwitch(string KeyNameValue, bool IStart)
{
if (IStart)
this.SetAutoValue(KeyNameValue);
else
this.DelAutoValue(KeyNameValue);
return;
}
string Auto = "Auto";
string AutoValue = "";
5、
是否啟用AutomaticOperation()
private void AutomaticOperation()
{
AutoValue = GetConfigValue("SetAutoValue");
this.IsValueExist("自啟運行");
try
{
if (Auto == AutoValue)
{
AutoStartSwitch("自啟運行", true);
}
if (Auto != AutoValue)
{
AutoStartSwitch("自啟運行", false);
}
}
catch (Exception)
{
return;
}
}
6、
下面是設定檔Touchscreenbrowser.xml
<?xml version="1.0" encoding="utf-8"?>
<Touchbrowser>
<SetAutoValue>Auto</SetAutoValue>
</Touchbrowser>
7、
讀取Touchscreenbrowser.xml檔案的函數GetConfigValue()
//獲得設定檔的值
protected string GetConfigValue(string configName)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Application.StartupPath + "/Touchscreenbrowser.xml");
XmlNodeList nodeList = xmlDoc.SelectSingleNode("Touchbrowser").ChildNodes;//擷取Touchbrowser節點的所有子節點
foreach (XmlNode xn in nodeList)//遍曆所有子節點
{
if (xn.Name == configName)
{
return xn.InnerText;
}
}
return "";
}
源碼下載 :http://download.csdn.net/source/645945