1

I have the following code that works fine on my Win 7 box - i.e lists the available printer and changes the selected to the default printer - moving the 'tick' the the correct printer. However when I run this on my terminal server box it list the printers okay but when I select the printer it removes the default printer completely (no tick against any printer) - any ideas ?

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;
4

1 回答 1

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;

希望对你有效。

于 2013-06-05T13:43:36.680 回答