Delphi 设置系统默认打印机

2016-08-22 10:23:51来源:http://amcto111.blog.51cto.com/351775/1346596作者:kindao人点击


获取默认打印机名:

functionTForm1.GetDefaultPrinterName:string;
var
iSize:Integer;
sIniFile,sSection,sKeyName:PChar;
begin
iSize:=256;
sIniFile:='win.ini';
sSection:='windows';
sKeyName:='device';
SetLength(Result,iSize);
GetPrivateProfileString(sSection,sKeyName,nil,PChar(Result),iSize,sIniFile);
Result:=Copy(Result,0,Pos(',',Result)-1);
end;

更改默认打印机:需要Uses WinSpool

procedureChangeDefaultPrinter(constName:string);
var
W2KSDP:function(pszPrinter:PChar):Boolean;stdcall;
H:THandle;
Size,Dummy:Cardinal;
PI:PPrinterInfo2;
begin
if(Win32Platform=VER_PLATFORM_WIN32_NT)and(Win32MajorVersion>=5)then
begin
@W2KSDP:=GetProcAddress(GetModuleHandle(winspl),'SetDefaultPrinterA');
if@W2KSDP=nilthenRaiseLastOSError;
ifnotW2KSDP(PChar(Name))thenRaiseLastOSError;
end
else
begin
ifnotOpenPrinter(PChar(Name),H,nil)thenRaiseLastOSError;
try
GetPrinter(H,2,nil,0,@Size);
ifGetLastError<>ERROR_INSUFFICIENT_BUFFERthenRaiseLastOSError;
GetMem(PI,Size);
try
ifnotGetPrinter(H,2,PI,Size,@Dummy)thenRaiseLastOSError;
PI^.Attributes:=PI^.AttributesorPRINTER_ATTRIBUTE_DEFAULT;
ifnotSetPrinter(H,2,PI,PRINTER_CONTROL_SET_STATUS)thenRaiseLastOSError;
finally
FreeMem(PI);
end;
finally
ClosePrinter(H);
end;
end;
end;//ChangeDefaultPrinterChangeDefaultPrinter函数在D7下使用SetDefaultPrinterA,在Delphi2010以上版本使用SetDefaultPrinterWprocedureTDM.ChangeDefaultPrinter(constName:string);
var
Device:array[0..255]ofChar;
Driver:array[0..255]ofchar;
Port:array[0..255]ofchar;
s:array[0..255]ofChar;
hDeviceMode:THandle;
I:Integer;
begin
forI:=0toPrinter.Printers.Count-1do
ifPrinter.Printers.Strings[I]=namethen
begin
Printer.PrinterIndex:=I;
Break;
end;
Printer.GetPrinter(Device,Driver,Port,hDeviceMode);
StrCopy(s,Device);
StrCat(s,',');
StrCat(s,Driver);
StrCat(s,',');
StrCat(s,Port);
WriteProfileString('windows','device',s);
StrCopy(s,'windows');
SendMessage(HWND_BROADCAST,WM_WININICHANGE,0,LongInt(@s));
end;//这个函数也可以更改打印机,效果没有上面的好

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台