Sets a printer by its HDC or name.
SetPrinterByName p$
SetPrinterHDC h
p$ | : sexp |
h | : handle |
SetPrinterHDC allows the printer to be set using a printer object's DC handle. This is particularly useful with the Dlg Print command.
SetPrinterByName allows for selecting a printer without using a common dialog box. The printer name p$ must exist, if not an error is generated. To be sure, use this command in a Try/Catch structure.
A list of existing printers can be obtained using App.PrinterCount and App.PrinterName().
Local h As Handle, n As Int32
OpenW 1
FontBold = True : Text 10, 10, "Select a Printer:" : FontBold = False
Ocx ListBox lb = "", 10, 25, 250, 100
For n = 1 To App.PrinterCount
lb.AddItem App.PrinterName(n), n
Next n
Ocx Command cmd = "Select", 85, 140, 100, 22 : cmd.Enabled = False
Do : Sleep : Until Win_1 Is Nothing
OpenW Hidden 1
Dlg Print Win_1, 0, h
If h <> 0
SetPrinterHDC h
// For some reason, DeviceName is returned as blank
Message "Printer Selected:" & #13#10 & Printer.DeviceName
PrintOut
EndIf
CloseW 1
Sub cmd_Click
SetPrinterByName lb.List(lb.ListIndex)
Message lb.List(lb.ListIndex) & " selected as current printer"
PrintOut
Win_1.Close
EndSub
Sub lb_Click
If lb.ListIndex <> -1 Then cmd.Enabled = True
EndSub
Sub PrintOut
Output = Printer
StartDoc "Test"
StartPage
FontSize = 12
Print "Success!"
EndPage
EndDoc
Output = Win_1
EndSub
The SetPrinter... commands only temporarily select a printer and do not change which printer is considered default. If the aim is to change to permamently change the default printer, a variation on the following code can be used:
Local obj As Object
Set obj = CreateObject("WScript.Network")
~obj.SetDefaultPrinter("EPSON BX305 Plus Series")
Set obj = Nothing
Prior to OCX v2.33/2.34, using SetPrinterByName could cause a buffer overflow as GFA BASIC 32 did not reserve enough memory for the information received from some more modern printers; there is no workaround for this (barring using Try/Catch to catch the error) so the only fix is to download the latest version of GfaWin23.ocx.
{Created by Sjouke Hamstra; Last updated: 04/03/2018 by James Gaite}