Programmatically Execute the Map Network Drive Dialog provides a custom "MapNetworkDrive" function accepts a UNC path and displays the standard Map Network Drive dialog.
This time, we want to remove a network connection from Delphi code...
Programmatically Execute the Disconnect Network Drives Dialog
If you want to programmatically call the Disconnect Network Drives Dialog in your Delphi application, you can do it by calling the WNetDisconnectDialog Windows API function. function DisconnectNetworkDriveDialog(const ownerHandle: THandle): boolean;
begin
result := WNetDisconnectDialog(ownerHandle, RESOURCETYPE_DISK) = NO_ERROR;
end;
Note: WNetDisconnectDialog returns -1 if the user cancels the dialog box.
Programmatically Remove a Network Drive
If you need to disconnect a mapped network drive silently, without displaying the "disconnect ..." dialog, use the following function: //disconnects a network drive
function DisconnectNetworkDrive(const drive: string; const force, restore, displayError: boolean): DWORD;
// force: should disconnection occur if there are open files or jobs on the connection
// restore: should continue to restore the connection at the next logon
// displayError: show the failure reason if any
var
return, dwFlags: DWORD;
begin
if restore then
dwFlags := CONNECT_UPDATE_PROFILE
else
dwFlags := 0;
return := WNetCancelConnection2(PChar(drive), dwFlags, force) ;
if (return <> NO_ERROR) and (displayError) then
begin
Application.MessageBox(PChar('Could not disconnect, reason:' + #13#10 +
SysErrorMessage(GetLastError)),
'DisconnectNetworkDrive',
MB_OK) ;
end;
result := return;
end;
Note: SysErrorMessage is used to convert the OS error code into a user friendly message.
Delphi tips navigator:
» Generic Solution to Freeing Objects in Delphi's TStringList Collections
« Programmatically Execute the Map Network Drive Dialog to Map a UNC Path to a Drive Letter Using Delphi


