2013-06-05 98 views
0

我有以下代碼可以在我的Win 7盒子上正常工作 - 即列出可用打印機並將所選內容更改爲默認打印機 - 將「打勾」移動到正確的打印機。但是,當我在終端服務器盒上運行它時,它列出了打印機,但是當我選擇打印機時,它會完全刪除默認打印機(不打印任何打印機) - 任何想法?使用Delphi代碼設置默認打印機終端服務

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

@RobKennedy:他表示打印機圖標上的刻度,表示默認打印機... – whosrdaddy

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

希望它爲你工作。

相關問題