How can I change the default printer on Windows 11? The following code works fine on Windows 10 but not on 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;
Printer preferences ‘Let Windows manage my default printer‘ is off and one printer set as default. I'm happy about any hint.
CodePudding user response:
As i see you use "old style" code. I think Microsoft already breaks capability with "WIN.INI"-file directly delivered from Win9X. Try to use generic WinApi solution for it. This should help: https://docs.microsoft.com/en-us/windows/win32/printdocs/setdefaultprinter
CodePudding user response:
Thanks, This code works for me:
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;