You can use the WNetUseConnection
function with CONNECT_INTERACTIVE
and CONNECT_PROMPT
flags. That will in combination with empty user ID and password parameters invoke the credentials dialog and connect to a network resource when you enter correct credentials:
procedure TForm1.Button1Click(Sender: TObject);
var
BufferSize: DWORD;
ResultFlag: DWORD;
NetResource: TNetResource;
begin
NetResource.dwType := RESOURCETYPE_DISK;
NetResource.lpLocalName := nil;
NetResource.lpRemoteName := '\\MySuperSecret\Place';
NetResource.lpProvider := nil;
if WNetUseConnection(Handle, NetResource, nil, nil, CONNECT_INTERACTIVE or
CONNECT_PROMPT, nil, BufferSize, ResultFlag) = NO_ERROR
then
ShowMessage('Connected!');
end;
To connect to a network resource without prompting for credentials remove the flags specified above as it's shown in the following function, which should return True, when the connection succeed, False when it fails. Here's the parameter description:
- RemoteName (string) - remote network name
- UserName (string) - user name used to connect to a network resource
- Password (string) - password used to connect to a network resource
function TryConnect(const RemoteName, UserName, Password: string): Boolean;
var
BufferSize: DWORD;
ResultFlag: DWORD;
NetResource: TNetResource;
begin
NetResource.dwType := RESOURCETYPE_DISK;
NetResource.lpLocalName := nil;
NetResource.lpRemoteName := PChar(RemoteName);
NetResource.lpProvider := nil;
Result := WNetUseConnection(0, NetResource, PChar(UserName), PChar(Password),
0, nil, BufferSize, ResultFlag) = NO_ERROR;
end;