Adding a network connection can be easily done by using map network drive in Network Neighborhood or My Computer, but it can be useful to be able to do this in Visual Basic. In this example you will learn how to create the connection using the Windows API and how to delete a connection as well.
- Start a new Standard-EXE project, form1 is created by default
- Add a standard module and add a command button to form1
- Type the following in the standard module.
Option Explicit Declare Function _ WNetAddConnection Lib _ "mpr.dll" Alias _ "WNetAddConnectionA" _ (ByVal lpszNetPath As String, _ ByVal lpszPassword As String, _ ByVal lpszLocalName _ As String) As Long Declare Function _ WNetCancelConnection _ Lib "mpr.dll" _ Alias "WNetCancelConnectionA _ " (ByVal lpszName _ As String, ByVal bForce As Long)_ As Long Const WN_SUCCESS = 0 ' _ The function was successful. Const WN_NET_ERROR = 2 ' _ An error occurred on the network. Const WN_BAD_PASSWORD = 6 ' _ The password was invalid. Function AddConnection _ (MyShareName As String, _ MyPWD As String, UseLetter _ As String) As Integer On Local Error GoTo _ AddConnection1_Err AddConnection = _ WNetAddConnection(MyShareName, _ MyPWD, UseLetter) AddConnection_End: Exit Function AddConnection_Err: AddConnection = Err MsgBox Error$ Resume AddConnection_End End Function Function CancelConnection _ (DriveLetter As String, _ Force As Integer) As Integer On Local Error GoTo _ CancelConnection_Err CancelConnection = _ WNetCancelConnection(DriveLetter, _ Force) CancelConnection_End: Exit Function CancelConnection_Err: CancelConnection = Err MsgBox Error$ Resume CancelConnection_End End Function
- to add a connection call by:
varible = AddConnection _ (<SharePath>, _ <Password>, _ <DriveLetter>)
- To cancel a connection type:
varible = CancelConnection _ (<SharePath, <Force>)
Run the project.