BP Forums
Making Your Program Start with Windows - Printable Version

+- BP Forums (https://bpforums.info)
+-- Forum: Archived Forums (https://bpforums.info/forumdisplay.php?fid=55)
+--- Forum: Archived Forums (https://bpforums.info/forumdisplay.php?fid=56)
+---- Forum: VB.NET (Visual Basic 2010/2008) (https://bpforums.info/forumdisplay.php?fid=8)
+----- Forum: Code Snippets (https://bpforums.info/forumdisplay.php?fid=18)
+----- Thread: Making Your Program Start with Windows (/showthread.php?tid=771)



Making Your Program Start with Windows - brandonio21 - 04-09-2013

I know I have received several PMs and emails regarding making your VB.NET application start with Windows, and I finally got around to creating a nice code snippet.

The first thing you need to do is as the "Windows Script Host Object Model" COM object as a reference to your project. This is very important.

Next, you will want to import the reference:
[code2=vbnet]Imports IWshRuntimeLibrary[/code2]

Now you're good to go and you can start your application with Windows. Essentially, this code will create a shortcut in the users "Startup" folder, forcing Windows to start the application when the computer is turned on.

This code will create the shortcut/start the program with Windows:
[code2=vbnet]'create path variables
Dim startupPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim executablePath As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
Dim executableName As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName
'create shortcut
Dim Shell As WshShell
Dim Link As WshShortcut
Try
Shell = New WshShell
Link = CType(Shell.CreateShortcut(startupPath & "\" & executableName & ".lnk"), IWshShortcut)
Link.TargetPath = executablePath
Link.Save()
Catch ex As Exception
MsgBox(ex.Message)
End Try[/code2]

This code will remove the shortcut/stop the program from starting with Windows:
[code2=vbnet]Dim startupPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim executableName As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName

Dim directoryInfo As New System.IO.DirectoryInfo(startupPath)
Dim fileInfo() As System.IO.FileInfo
fileInfo = directoryInfo.GetFiles("*.lnk")
For Each file As System.IO.FileInfo In fileInfo
If (file.FullName.Contains(executableName)) Then
file.Delete()
End If
Next[/code2]


Optionally, you can eliminate the deletion of files with similar names by changing file.FullName.Contains(executableName) to file.FullName.Equals(executableName)


Watch the video here: <!-- m --><a class="postlink" href="http://www.youtube.com/watch?v=VpPqPtTjMzQ&feature=youtu.be">http://www.youtube.com/watch?v=VpPqPtTj ... e=youtu.be</a><!-- m -->


[attachment=0]<!-- ia0 -->StartupTest.zip<!-- ia0 -->[/attachment]