C#-winform 開機啟動程式 -啟動表

C#-winform 開機啟動程式 登錄表+啟動表

最近在幫公司做一個開機可以自動執行的程式

發現如果只有登錄表的話,程式會”啟動不完全”(可能會有程式無法動作)或是不正常動作,所以改使用啟動表做

下面均提通啟動表與登錄表的程式碼

程式分成4部分

登錄表

 string app_name = System.IO.Path.GetFileName(Application.ExecutablePath);//檔名
 string path = Application.ExecutablePath; //程式位置
 try
 {
     RegistryKey rk = Registry.LocalMachine;
     RegistryKey rk2 = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);

     if (rk2.GetValue(app_name) != null)
     {
         rk2.DeleteValue(app_name, false);
     }
     rk2.SetValue(app_name, path + " -autostart"); //-autostart用來識別是否為開機啟動
     rk2.Close();
     rk.Close();
 }
 catch (Exception ex)
 {
     MessageBox.Show("fail\n");
 }

啟動表

先增加參考 – COM->windows scriot host object model

Create(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "捷徑名稱", this.GetType().Assembly.Location) //設定

//製作捷徑到啟動表
public static bool Create(string directory, string shortcutName, string targetPath, string description = null, string iconLocation = null)
{
    try
    {
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        //新增引用 Com 中搜尋 Windows Script Host Object Model
        string shortcutPath = Path.Combine(directory, string.Format("{0}.lnk", shortcutName));
        IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
        IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutPath);//建立快捷方式物件
        shortcut.TargetPath = targetPath;//指定目標路徑
        shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//設定起始位置
        shortcut.WindowStyle = 1;//設定執行方式,預設為常規視窗
        shortcut.Description = description;//設定備註
        shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//設定圖示路徑
        shortcut.Save();//儲存快捷方式
        return true;
    }
    catch
    { }
    return false;
}

判斷是否為自動啟動

public static bool AutoRun()
{
    string[] strArgs = Environment.GetCommandLineArgs(); //取得執行命令列
    if (strArgs.Count() >= 2)
    {
        //MessageBox.Show(strArgs[1]);
        if (strArgs[1].Contains("autostart"))//判斷引述(自動啟動的部分)
        {
            return true;
        }
    }
    return false;

}

在winform 的form 的shown事件中增加

private void Form1_Shown(object sender, EventArgs e)
{
    if (logClass.AutoRun())
    {        
        Thread a = new Thread(() => { 
            ProcessStartInfo startInfo = new ProcessStartInfo( this.GetType().Assembly.Location);//設定執行檔名稱
            startInfo.UseShellExecute = false;//要加這行才能正常執行
            startInfo.Arguments = "";//傳入參數
            startInfo.CreateNoWindow = true;
            Process.Start(startInfo);//啟動 startInfo
            Environment.Exit(Environment.ExitCode);
            });
        a.IsBackground = false;
        a.Start();
    }
}