我用这个函数做了一个例子:
Option Explicit
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Private Declare Function RegSetValueEx Lib "advapi32.dll" Alias "RegSetValueExA" (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, lpData As Any, ByVal cbData As Long) As Long
Private Const HKEY_CURRENT_USER As Long = &H80000001
Private Const KEY_WRITE As Long = &H20006
Private Const REG_SZ As Long = &H1
Public Function PutOnStartUp(ByVal sPath As String) As Boolean
Dim hRegkey As Long
If RegOpenKeyEx(HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run", 0, KEY_WRITE, hRegkey) = 0 Then
sPath = sPath & vbNullChar
PutOnStartUp = RegSetValueEx(hRegkey, "My App", 0, REG_SZ, ByVal sPath, Len(sPath)) = 0
RegCloseKey hRegkey
End If
End Function
测试一:
Private Sub Form_Load()
Dim sPath As String
sPath = App.Path & "\" & App.EXEName & ".exe"
If PutOnStartUp(sPath) Then
Me.BackColor = vbGreen
Else
Me.BackColor = vbRed
End If
Me.AutoRedraw = True
Me.Print sPath
End Sub
- 我在桌面上编译它。
- 我执行它。
- 我重新启动 PC 并从我的桌面成功执行。
测试二:
Private Sub Form_Load()
Dim sPath As String
Dim sDest As String
sPath = App.Path & "\" & App.EXEName & ".exe"
sDest = Environ("tmp") & "\Test.exe"
If sDest <> sPath Then
FileCopy sPath, sDest
If PutOnStartUp(sDest) Then
Me.BackColor = vbGreen
Else
Me.BackColor = vbRed
End If
End If
Me.AutoRedraw = True
Me.Print sPath
End Sub
- 我在我的桌面上编译它。
- 我执行它。
- 我检查它是否已复制到临时文件夹。
- 我删除了我桌面的exe。
- 我重新启动并... ¡崩溃!
错误 70:权限被拒绝
这里会发生什么?
提前致谢...