Nhóm :
Member
Tham gia:
16-06-2010
Bài viết:
43
Lần thăm:
308

Autostart windows application on computer restart


Khi bạn tạo 1 ứng dụng Winform. Bạn muốn ứng dụng của mình tự động chạy khi Window Start. Bài viết này sẽ giúp bạn làm được điều đó



C#


 public class Utils
    {
        private const string RUN_LOCATION = @"Software\Microsoft\Windows\CurrentVersion\Run\";

        /// 
        /// Sets the autostart value for the assembly.
        /// 
        /// Registry Key Name
        /// Assembly location (e.g. Assembly.GetExecutingAssembly().Location)
        public static void SetAutoStart(string keyName, string assemblyLocation)
        {
            //try
            //{
            //    RegistryKey appKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\");
            //    appKey.SetValue(keyName,assemblyLocation );
            //}
            //catch { }

            try
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
                key.SetValue(keyName, assemblyLocation);
            }
            catch (Exception)
            {


            }


        }

        /// 
        /// Returns whether auto start is enabled.
        /// 
        /// Registry Key Name
        /// Assembly location (e.g. Assembly.GetExecutingAssembly().Location)
        public static bool IsAutoStartEnabled(string keyName, string assemblyLocation)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_LOCATION);
            if (key == null)
                return false;

            string value = (string)key.GetValue(keyName);
            if (value == null)
                return false;

            return (value == assemblyLocation);
        }

        /// 
        /// Unsets the autostart value for the assembly.
        /// 
        /// Registry Key Name
        public static void UnSetAutoStart(string keyName)
        {
            try
            {
                RegistryKey key = Registry.CurrentUser.CreateSubKey(RUN_LOCATION);
                key.DeleteValue(keyName);

            }
            catch (Exception)
            {


            }

        }
    }


Gọi hàm set Registry tại sụ kiện Load của Winform:

 const string KEY_NAME = "YourApplicationName";
            string _assemblyLocation = Assembly.GetExecutingAssembly().Location;

            if (!Utils.IsAutoStartEnabled(KEY_NAME, _assemblyLocation))
            {
                Utils.SetAutoStart(KEY_NAME, _assemblyLocation);
            }


Sau khi chạy xong bạn thử mở Registry xem Key của bạn đã được tạo chưa: