KnowDotNet NetRefactor

Creating a Desktop Shortcut in .NET Code

Use Com Interop to Access the Windows Scripting Object

by Les Smith
Print this Article Discuss in Forums

How do I create a Shortcut on the Desktop from VB.NET or C#.Net?  I also need to pass a user id and password so that I can launch the program and log it on to the database without the user having to login.  In VB6, you had to use the Windows Scripting DLL.  In .NET, since this facility has not been moved to the Framework, you still must use the same approach through Com Interop.

To get started creating a Shortcut on the Desktop, you must include a Reference to the Windows Scripting Library.  You do this by right-clicking on the References folder in the Solution Explorer.  Select the Add Reference menu.  From the Add Reference dialog, click the Com Tab and select the Windows Scripting Host Object Model and click the Add button.

Next, add the following Imports (VB.NET)

Imports IWshRuntimeLibrary

or using (C#) statement.


using IWshRuntimeLibrary;

The following method does the work of creating the shortcut on the Desktop.  Since I want the shortcut to launch the application and login to the database, this method needs the userID and passWord passed into it so that they can be added to the parameters of the application that I will launch from the shortcut.  Obviously, the first time that this application runs, it will prompt the user for their userID and passWord and save it in the shortcut.  From then on, if they choose to create a shortcut, the shortcut will automatically have the userID and passWord passed to it on the Command line.

   Public Function CreateShortCutOnDesktop(ByVal userID As String, _
      
ByVal passWord As String) As Boolean
      Try
         Dim DesktopDir As String = _
            
CType(WshShell.SpecialFolders.Item("Desktop"), String)
        
Dim shortCut As IWshRuntimeLibrary.IWshShortcut

        
' short cut files have a .lnk extension
         shortCut = CType(WshShell.CreateShortcut(DesktopDir & _
          
"\MyNewShortcut.lnk"), _
             IWshRuntimeLibrary.IWshShortcut)

        
' set the shortcut properties
         With shortCut
            .TargetPath = _
               System.Reflection.Assembly.GetExecutingAssembly.Location()
            .WindowStyle = 1
            .Description =
"Run Typist Summary"
            .WorkingDirectory = DesktopDir
            ' the next line gets the first Icon from the executing program
            .IconLocation = _
              System.Reflection.Assembly.GetExecutingAssembly.Location() & _
              
", 0"
           ' the next line sets the userID and passWord into the shortcut
            ' as arguments
            ' which will be read from the command line.

            .Arguments = userID &
", " & passWord
            .Save()
' save the shortcut file
         End With
         Return True
      Catch ex As System.Exception
        
' add your error handling here, if any
        
Return False
      End Try
   End Function

Next, I will show you the startup code for the application.  It checks to see if the userID and passWord were passed in on the Command line.  That will happen once the shortcut has been created.  If the parameters are there, we do not need to prompt the user for their login information; we already have it and we can log them in automatically.  If the parameters are not extant, we will load the Login form to get the parameters.  On that form I will have a Checkbox to allow the user to request the creation of a shortcut for automatic login for subsequent usage of the application.  You will notice the use of two utility functions MNS() and MNI().  These two functions simply guarantee that the passed in arguments (database fields) are returned as non null default values for String and Integer.  In this application, I am also using a XML Web Service to access the database, because I have written both a Windows Forms application and an ASP.NET application that that the app can be run in-house and from the Internet.  I have also used a Regular Expression to parse the userID and passWord.

   Public Sub Main()
      
' application starts here
      ' if the app is started with command line arguments, then
      ' it was started from an icon and we can use the arguments to
      ' get the data to pass directly to the main grid form, otherwise
      ' show the login form
      Dim cmdLine As String = Microsoft.VisualBasic.Command
      
If cmdLine.Trim.Length = 0 Then
        
' load the Login form since no login data was passed in
         RunLogin()
      
Else
         Dim m As Match
         m = Regex.Match(cmdLine,
"^\s*(?<id>\w+)\s*,*\s*(?<pw>\w*)")
        
If Not m.Success Then
            Dim f As New frmLogin
            RunLogin()
        
Else
            
' retrieve the passed in parameters and get the login data to validate
            ' that the parameters match the user's id and password

            Dim id As String = m.Groups("id").Value
            
Dim pw As String = m.Groups("pw").Value
            
Dim ws As New localhost.MyWebService
            
Dim ds As DataSet = ws.GetAppLogonData(CInt(id))
            
Dim dt As DataTable = ds.Tables(0)
            
If dt.Rows.Count = 0 OrElse _
               IsDBNull(MNS(dt.Rows(0).Item(
"password"))) OrElse _
               pw <> MNS(dt.Rows(0).Item(
"password")) Then
               MsgBox("Invalid UserID or Password Code.", MsgBoxStyle.Exclamation)
               RunLogin()
            
End If
            Dim userID As Integer = MNI(dt.Rows(0).Item("userid"))
            
Dim secCode As String = MNS(dt.Rows(0).Item("password"))
            
Dim userName As String = MNS(dt.Rows(0).Item("lname")) & ", " & _
               MNS(dt.Rows(0).Item(
"fname"))
            
Dim f As New frmMain(userID, passWord, userName)
            Application.Run(f)
        
End If
      End If
   End Sub

I wrote the following function to return True if the shortcut already exists, so that I don't prompt the user again to determine if they want to creat the shortcut.


   Public Function IsShortcutExtant() As Boolean
      Dim deskTopDir As String = _
        
CType(WshShell.SpecialFolders.Item _
          (
"Desktop"), String)
      
If IO.File.Exists(deskTopDir & _
        
"\MyNewShortcut.lnk") Then
         Return True
      Else
         Return False
      End If
   End Function


I have shown the code in VB.NET, although I now do at least half of my coding in C#.  In VB, you can now do almost all of the things that, years ago, would have had to be done in a lower level language.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing