更改Windows 11的默认打印机[delphi] [Windows -11] [printing]



如何更改Windows 11的默认打印机?下面的代码在Windows 10上可以正常工作,但在Windows 11上不行:

procedure TForm1.SetDefaultPrinter(NewDefPrinter: string);
var
ResStr: array [0 .. 255] of char;
begin
StrPCopy(ResStr, NewDefPrinter);
WriteProfileString('windows', 'device', ResStr);
StrCopy(ResStr, 'windows');
SendNotifyMessage(HWND_BROADCAST, WM_WININICHANGE, 0, LongInt(@ResStr));
end; 

打印机首选项"让Windows管理我的默认打印机"关闭,并将一台打印机设置为默认打印机。我对任何提示都很高兴。

我看你用的是" old style ";代码。我认为微软已经打破了Win9X直接提供的"win . ini"文件的功能。尝试使用通用的WinApi解决方案。这应该会有所帮助:https://learn.microsoft.com/en-us/windows/win32/printdocs/setdefaultprinter

谢谢,这个代码为我工作:

procedure TForm1.SetDefaultPrinter(Name: string);
var
fnSetDefaultPrinter: function(pszPrinter: PChar): Bool; stdcall;
H: THandle;
Size, Dummy: Cardinal;
PrinterInfo: PPrinterInfo2;
begin
if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 5) then begin
@fnSetDefaultPrinter := GetProcAddress(GetModuleHandle(winspl), 'SetDefaultPrinterW');
if (@fnSetDefaultPrinter = NIL) then
RaiseLastOSError;
if NOT fnSetDefaultPrinter(PChar(Name)) then
RaiseLastOSError;
end
else begin
if NOT OpenPrinter(PChar(Name), H, NIL) then
RaiseLastOSError;
try
GetPrinter(H, 2, NIL, 0, @Size);
if GetLastError <> ERROR_INSUFFICIENT_BUFFER then
RaiseLastOSError;
GetMem(PrinterInfo, Size);
try
if NOT GetPrinter(H, 2, PrinterInfo, Size, @Dummy) then
RaiseLastOSError;
PrinterInfo^.Attributes := PrinterInfo^.Attributes or PRINTER_ATTRIBUTE_DEFAULT;
if NOT Winspool.SetPrinter(H, 2, PrinterInfo, PRINTER_CONTROL_SET_STATUS) then
RaiseLastOSError;
finally
FreeMem(PrinterInfo);
end;
finally
ClosePrinter(H);
end;
end;
end;

最新更新