更改Windows 11上的默认打印机[ Delphi ] [windows-11] [打印]

wvmv3b1j  于 2022-11-04  发布在  Windows
关注(0)|答案(2)|浏览(467)

如何在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管理我的默认打印机”已关闭,一台打印机已设置为默认打印机。我很高兴听到任何提示。

xvw2m8pv

xvw2m8pv1#

正如我看到你使用“老式”代码。我认为微软已经打破了“WIN.INI”的功能-文件直接从Win 9 X交付。尝试使用通用的WinApi解决方案。这应该有帮助:https://learn.microsoft.com/en-us/windows/win32/printdocs/setdefaultprinter

e4eetjau

e4eetjau2#

谢谢,这段代码对我有用:

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;

相关问题