The following describes how to create a Windows shortcut from VB .NET code.
Step 1. Create a new VB .NET project or open an existing one. Step 2. Right-click 'References' in the Solution Explorer and click 'Add reference...' Step 3. Select the 'COM' tab and scroll down to 'Windows Script Host Object Model'. Click 'OK' and a reference to 'IWshRuntimeLibrary' should be added. Step 4. Open the form or class you wish to write your code in for adding the shortcut and add the next line at the top:
CODE
Imports IWshRuntimeLibrary
Step 5. Add the following function to your class:
CODE
Private Function CreateShortCut(ByVal shortcutName As String, ByVal creationDir As String, ByVal targetFullpath As String, ByVal workingDir As String, ByVal iconFile As String, ByVal iconNumber As Integer) As Boolean Try If Not IO.Directory.Exists(creationDir) Then Dim retVal As DialogResult = MsgBox(creationdir & " does not exist. Do you wish to create it?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo) If retVal = DialogResult.Yes IO.Directory.CreateDirectory(creationDir) Else Return False End If End If
Dim shortCut As IWshRuntimeLibrary.IWshShortcut shortCut = CType(wShell.CreateShortcut(creationDir & "\" & shortcutName & ".lnk"), IWshRuntimeLibrary.IWshShortcut) shortCut.TargetPath = targetFullpath shortCut.WindowStyle = 1 shortCut.Description = shortcutName shortCut.WorkingDirectory = workingDir shortCut.IconLocation = iconFile & ", " & iconNumber shortCut.Save() Return True Catch ex As System.Exception Return False End Try End Function
The CreateShortCut function requires 6 parameters: - shortCutName : The name of the shortcut - creationDir : The folder where the shortcut should be created - targetFullpath : The full path to the target file - workingDir : The folder to use as working directory for the target of the shortcut - iconFile : The file that contains the icon for the shortcut - iconNumber : The position of the icon within the icon file. This is zero if the icon file is an icon itself.
The function returns false if the creation of a shortcut has failed. An example of calling the function:
The code above creates a shortcut named 'My Application' on the desktop of the current user, pointing to the current application's executable, using the current application's folder as the working directory. It extracts icon number 4 from the library 'myAppExtensions.dll".
You can extract icons from any library or executable containing them. Commonly used icons can be found in Shell32.dll for example. You can also use an .ico file and set iconNumber to 0 (zero) to use it.