Problemstellung:
Wie kann ich mit API ein Netzlaufwerk verbinden bzw. die Verbindung aufheben?
1. Benötige API's und Konstanten:
' Netzlaufwerkfunktionen per Dialog Public Declare Function WNetConnectionDialog Lib "mpr.dll" ( _ ByVal hWnd As Long, _ ByVal dwType As Long) As Long Public Declare Function WNetDisconnectDialog Lib "mpr.dll" ( _ ByVal hWnd As Long, _ ByVal dwType As Long) As Long ' Netzlaufwerkfunktionen ohne Dialog Public Declare Function WNetAddConnection Lib "mpr.dll" _ Alias "WNetAddConnectionA" ( _ ByVal lpszNetPath As String, _ ByVal lpszPassword As String, _ ByVal lpszLocalName As String) As Long Public Declare Function WNetCancelConnection Lib "mpr.dll" _ Alias "WNetCancelConnectionA" ( _ ByVal lpszName As String, _ ByVal bForce As Long) As Long Public Const RESOURCETYPE_DISK = &H1 Public Const WN_Success = &H0 Public Const WN_Net_Error = &H2 Public Const WN_Bad_Password = &H6 Public Const WN_Access_Denied = &H7 Public Const WN_Already_Connected = &H34 Public Const WN_Bad_NetName = &H32
2. Verbinden per Dialog (im Formular):
Dim lResult As Long lResult = WNetConnectionDialog(Me.hWnd, _ RESOURCETYPE_DISK)
Ergebnis:
3. Verbindung per Dialog aufheben (im Formular):
Dim lResult As Long lResult = WNetDisconnectDialog(Me.hWnd, _ RESOURCETYPE_DISK)
Ergebnis:
4. Verbinden per Code:
Diese Funktionen unterstützen keine Übergabe des Usernamens und des Profils
Das wird ein extra Thema.
Public Function Connect_NetDrive(sDriveLetter As String, _ sNetworkPath As String, _ Optional sPWD As String = vbNullString) As Boolean Dim lResult As Long lResult = WNetAddConnection(sNetworkPath, _ sPWD, sDriveLetter) If lResult <> WN_Success Then Select Case lResult Case WN_Net_Error MsgBox "Netzwerkfehler!" Case WN_Bad_Password MsgBox "Ungültiges Passwort!" Case WN_Access_Denied MsgBox "Zugriff verweigert" Case WN_Already_Connected MsgBox "Laufwerk ist bereits verbunden" Case WN_Bad_NetName MsgBox "Der Netzwerkpfad wurde nicht gefunden" Case Else MsgBox "Unbekannter Fehler" End Select End If Connect_NetDrive = (lResult = WN_Success) End Function
Aufruf z.B.:
ohne Passwort:
Connect_NetDrive "E:", "\\PC-Name\Freigabename"
mit Passwort:
Connect_NetDrive "E:", \\PC-Name\Freigabename, "geheim"
5. Verbindung aufheben per Code:
Public Function Disconnect_NetDrive(sDriveLetter As String) As Boolean Dim lResult As Long lResult = WNetCancelConnection(sDriveLetter, True) If lResult <> WN_Success Then If lResult = WN_Net_Error Then MsgBox "Netzwerkfehler!" Else MsgBox "Unbekannter Fehler" End If End If Disconnect_NetDrive = (lResult = WN_Success) End Function
Aufruf z.B.:
Disconnect_NetDrive "K:"
Ähnliche Artikel
Weiterlesen...