如何更改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管理我的默认打印机”已关闭,一台打印机设置为默认。任何暗示我都很高兴。
发布于 2022-07-15 10:22:17
如我所见,你使用的是“旧式”代码。我认为微软已经打破了"WIN.INI"-file直接从Win9X交付的能力。尝试使用通用的WinApi解决方案。这应该会有帮助:https://learn.microsoft.com/en-us/windows/win32/printdocs/setdefaultprinter
发布于 2022-07-18 06:25:31
谢谢,这段代码适用于我:
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;
https://stackoverflow.com/questions/72991606
复制相似问题