// This function prints a test page on a specified printer.
// It may be used for local or remote host. When used for local host
// Destination, UserName and Password parameters must be empty.
// For remote computer, parameters must be:
// TargetHost: name or IP address of the remote host, like '10.8.36.54'
// UserName: name of the user, may include domain, like 'MOON\Administrator';
// Password: the user's password.
// Printer: the name of the printer where the test page is to be printed.
// ListPrinters function returns such names.
// See "How to list installed printers?" topic.
// The method returns empty string on success and error description otherwise
function PrintTestPage(Destination, UserName, Password, Printer: string): string;
var
Query: TWmiQuery;
Connection: TWmiConnection;
Method: TWmiMethod;
begin
Result := '';
Query := TWmiQuery.Create(nil);
Connection := TWmiConnection.Create(nil);
Method := TWmiMethod.Create(nil);
try
try
Connection.MachineName := Destination;
Connection.Credentials.UserName := UserName;
Connection.Credentials.Password := Password;
Connection.Connected := true;
Query.WQL.Text := 'select * from Win32_Printer';
Query.Connection := Connection;
Query.Open;
Method.WmiObjectSource := Query;
if not Query.Locate('Name', Printer, []) then
raise Exception.Create('Printer not found: ' + Printer);
Method.WmiMethodName := 'PrintTestPage';
if Method.Execute <> 0 then
begin
Result := Method.LastWmiErrorDescription;
if Result = '' then Result := 'Error ' + IntToStr(Method.LastWmiError);
end;
finally
Method.Free;
Query.Free;
Connection.Free;
end;
except
on E: Exception do Result := E.Message;
end;
end;
|