我有以下代码在我的Win 7盒子上工作正常 - 即列出可用的打印机并将所选的更改为默认打印机 - 将'tick'移动到正确的打印机上。然而,当我在我的终端服务器盒上运行它时,它列出了打印机没问题但是当我选择打印机时它完全删除了默认打印机(没有任何打印机打勾) - 任何想法?
uses Printers;
function GetDefaultPrinter: string;
var
ResStr: array[0..255] of Char;
begin
GetProfileString('Windows', 'device', '', ResStr, 255);
Result := StrPas(ResStr);
end;
procedure SetDefaultPrinter(NewDefPrinter: string);
var
ResStr: array[0..255] of Char;
begin
StrPCopy(ResStr, NewdefPrinter);
WriteProfileString('windows', 'device', ResStr);
StrCopy(ResStr, 'windows');
SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0, Longint(@ResStr));
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
//Fill the combobox with all available printers
Combobox1.Items.Clear;
Combobox1.Items.AddStrings(Printer.Printers);
// Get the Default Printer:
label1.Caption := Format('Default Printer: %s',[GetDefaultPrinter]);
end;
procedure TfrmMain.Button2Click(Sender: TObject);
begin
//Set the selected printer in the combobox as default printer
if Combobox1.Text <> '' then
SetDefaultPrinter(Combobox1.Text)
else ShowMessage('Choose a Printer first !');
end;
答案 0 :(得分:0)
您可以尝试使用以下内容:
procedure SetDefaultPrinter2(NewDefPrinter: string);
var
I: Integer;
Device: PChar;
Driver: PChar;
Port: PChar;
HdeviceMode: THandle;
aPrinter: TPrinter;
begin
Printer.PrinterIndex := -1;
GetMem(Device, 255);
GetMem(Driver, 255);
GetMem(Port, 255);
aPrinter := TPrinter.Create;
try
for I := 0 to Printer.Printers.Count - 1 do
begin
if Printer.Printers[I] = NewDefPrinter then
begin
aprinter.PrinterIndex := I;
aPrinter.getprinter(Device, Driver, Port, HdeviceMode);
StrCat(Device, ',');
StrCat(Device, Driver);
StrCat(Device, Port);
WriteProfileString('windows', 'device', Device);
StrCopy(Device, 'windows');
SendMessage(HWND_BROADCAST, WM_WININICHANGE,
0, Longint(@Device));
break;
end;
end;
finally
aPrinter.Free;
end;
FreeMem(Device, 255);
FreeMem(Driver, 255);
FreeMem(Port, 255);
end;
希望它适合你。