How to set the port for a specific printer (Views: 27)
Problem/Question/Abstract: I want to change the default printer and its settings (port) under Win 9x so that it affects all other applications for automated document printing to files (not from my application, from others like CorelDraw and Word...). I tried to this by changing the registry entries for the printers, but these changes only take effect after rebooting the system. Is there an API function that causes windows to update the printer settings from the registry? Or any other API function that directly affects the system wide printer settings? Answer: Setting a port for a specific printer: uses WinSpool; { Function SetPrinterToPort Parameters : hPrinter: handle of printer to change, obtained from OpenPrinter port: port name to use, e.g. LPT1:, COM1:, FILE: Returns: The name of the previous port the printer was attached to. Description: Changes the port a printer is attached to using Win32 API functions. The changes made are NOT local to this process, they will affect all other processes that try to use this printer! It is recommended to set the port back to the old port returned by this function after the end of the print job. Error Conditions: Will raise EWin32Error exceptions if SetPrinter or GetPrinter fail. Created: 21.10.99 by P. Below} function SetPrinterToPort(hPrinter: THandle; const port: string): string; var pInfo: PPrinterInfo2; bytesNeeded: DWORD; begin {Figure out how much memory we need for the data buffer. Note that GetPrinter is supposed to fail with a specific error code here. The amount of memory will be larger than Sizeof(TPrinterInfo2) since variable amounts of data are appended to the record} SetLastError(NO_ERROR); GetPrinter(hPrinter, 2, nil, 0, @bytesNeeded); if GetLastError <> ERROR_INSUFFICIENT_BUFFER then RaiseLastWin32Error; pInfo := AllocMem(bytesNeeded); try if not GetPrinter(hPrinter, 2, pInfo, bytesNeeded, @bytesNeeded) then RaiseLastWin32Error; with pInfo^ do begin Result := pPortname; pPortname := @port[1]; end; if not SetPrinter(hPrinter, 2, pInfo, 0) then RaiseLastWin32Error; finally FreeMem(pInfo); end; end; function GetCurrentPrinterHandle: THandle; var Device, Driver, Port: array[0..255] of char; hDeviceMode: THandle; begin Printer.GetPrinter(Device, Driver, Port, hDeviceMode); if not OpenPrinter(@Device, Result, nil) then RaiseLastWin32Error; end; |