この関数を使用して例を作成しました。
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
テスト 1:
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 を再起動すると、デスクトップから効果的に正常に実行されました。
テスト 2:
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: 権限が拒否されました
そこで何が起こるの?
前もって感謝します...