65.9K
CodeProject 正在变化。 阅读更多。
Home

自动运行应用程序

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.78/5 (11投票s)

2006年11月28日

CPOL

2分钟阅读

viewsIcon

43492

downloadIcon

558

本文将向您展示如何自动在启动时运行您的应用程序。

引言

您是否想过如何让您的程序在启动计算机时自动运行?一种简单的方法是将程序的快捷方式添加到当前用户的“启动”目录中,但这不太专业(尽管有些程序就是这样做的)。更好的方法是通过注册表,它允许更轻松地访问/删除启动项。

Using the Code

现在,由于我们正在访问注册表,您需要导入 Microsoft.Win32,其中包含 .NET Framework 处理注册表的部分。

有两个不同的注册表目录处理启动项:HKEY_Current_UserHKEY_Local_Machine。当前用户将仅为当前用户启动程序,而本地机器将为任何使用计算机的人启动程序。

要将启动项添加到 Current_User,您需要打开注册表项并设置值,如下所示

Private Sub AddCurrentKey(ByVal name As String, ByVal path As String)
   Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(_
                             "Software\Microsoft\Windows\CurrentVersion\Run", True)
   key.SetValue(name, path)
End Sub

并且要删除它

Private Sub RemoveCurrentKey(ByVal name As String)
   Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(_
              "Software\Microsoft\Windows\CurrentVersion\Run", True)
   key.DeleteValue(name, False)
End Sub

现在,我正在使用一个复选框来确定是否设置了注册表启动项。 “name”(名称)和“path”(路径)将在调用设置注册表值的函数时设置。

If CurrentStartup.Checked Then
   AddCurrentKey("StartupExample", _
                 System.Reflection.Assembly.GetEntryAssembly.Location)
Else
   RemoveCurrentKey("StartupExample")
End If

StartupExample 是项目的名称,也将是注册表项中设置的名称。System.Reflection.Assembly.GetEntryAssembly.Location 获取程序当前位置以存储在注册表项中。 另外,您可以通过使用 System.Reflection.Assembly.GetEntryAssembly.FullName 来设置启动项的“name”(名称),而不是指定它。

现在,要在 Local_Machine 中设置相同的启动项,只需将 CurrentUser 更改为 LocalMachine 即可。

关注点

在卸载程序时,将卸载程序设置为删除程序使用的所有注册表项始终是一个好主意。 这可以节省注册表混乱、计算机速度以及 Windows 尝试启动程序但由于未删除注册表项而找不到程序时崩溃的风险。

© . All rights reserved.