这几个函数完全能解决你的问题。
{-----------------------------}
procedure GetPrinterNames(pnl:TStringList);
var
buffer: TPrinterBuffer;
currPos: integer;
printerName: string;
begin
pnl.Clear;
if GetProfileString(PChar('PrinterPorts'), nil, '', buffer, MAXPRINTERBUFFER) > 0 then
begin
currPos := 0;
while (true)do
begin
printerName := ParseNames(buffer, currPos);
if printerName <> '' then
pnl.Add(printerName)
else
break;
end;
end;
end;
function ParseNames(const namebuffer: TPrinterBuffer;var startPos: integer): string;
var
i, j, NameLength: integer;
str: string;
begin
result := '';
if (startPos > High(namebuffer)) or (namebuffer[startPos] = Chr(0)) then
exit;
for i := startPos to High(namebuffer)do
begin
if namebuffer = Chr(0) then
begin
nameLength := i - startPos;
SetLength(str, nameLength);
for j := 0 to nameLength - 1do
str[j+1] := namebuffer[startPos + j];
result := str;
startPos := i + 1;
break;
end;
end;
end;
function SetPrinter(const PrinterName: String): boolean;
var
s2 : string;
dum1 : Pchar;
xx, qq : integer;
const
cs1 : pchar = 'Windows';
cs2 : pchar = 'Device';
cs3 : pchar = 'Devices';
cs4 : pchar = #0;
begin
xx := 254;
GetMem( dum1, xx);
Result := False;
try
qq := GetProfileString( cs3, pchar( printerName ), #0, dum1, xx);
if (qq > 0) and (trim( strpas( dum1 )) <> '') then
begin
s2 := PrinterName + ',' + strpas( dum1 );
while GetProfileString( cs1, cs2, cs4, dum1, xx) > 0do
WriteProfileString( cs1, cs2, #0);
WriteProfileString( cs1, cs2, pchar( s2 ));
case Win32Platform of
VER_PLATFORM_WIN32_NT :
// SendMessage( HWND_BROADCAST, WM_WININICHANGE, 0, LongInt(cs1));
// VER_PLATFORM_WIN32_WINDOWS :
// SendMessage( HWND_BROADCAST, WM_SETTINGCHANGE, 0, LongInt(cs1));
end;
Result := True;
end;
finally
FreeMem( dum1 );
end;
end;
function GetDefaultPrinter: string;
var
ResStr: array[0..255] of Char;
begin
GetProfileString('Windows', 'device', '', ResStr, 255);
Result := leftstr(trim(StrPas(ResStr)),pos(',',trim(StrPas(ResStr)))-1);
end;
{----------------------------------}