Set default printer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sashi
    Recognized Expert Top Contributor
    • Jun 2006
    • 1749

    Set default printer

    Set default printer

    You will often find yourself in a position where you have designed a report format for one printer and when that report is sent to another printer the layout is messed up.

    The following code will allow you to specify the printer that reports are sent to by reseting the systems default printer.

    Windows API/Global Declarations
    [code=vb]
    Public Declare Function WriteProfileStr ing Lib "kernel32" Alias "WriteProfileSt ringA" (ByVal lpszSection As String, ByVal lpszKeyName As String, ByVal lpszString As String) As Long

    Public Declare Function SendMessage Lib "user32" Alias "SendMessag eA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
    Public Const HWND_BROADCAST = &HFFFF&
    Public Const WM_WININICHANGE = &H1A
    [/code]

    Code
    [code=vb]
    Public Function SetDefaultPrint er(objPrn As Printer) As Boolean
    Dim x As Long, sztemp As String
    sztemp = objPrn.DeviceNa me & "," & objPrn.DriverNa me & "," & objPrn.Port
    x = WriteProfileStr ing("windows", "device", sztemp)
    x = SendMessage(HWN D_BROADCAST, WM_WININICHANGE , 0&, "windows")
    End Function

    Private Sub Command1_Click( )
    Dim x As Printer
    If MsgBox("Are You Sure Want To Set " & Combo1.Text & " as Default printer ? ", vbYesNo, "Attention" ) = vbYes Then

    For Each x In Printers
    If x.DeviceName = Combo1.Text Then
    SetDefaultPrint er x
    Exit Sub
    End If
    Next

    End If
    End Sub

    Private Sub Form_Load()
    Dim x As Printer
    Dim y As Integer
    y = 0

    With Combo1 'Scan all available printer and put them
    For Each x In Printers 'in To combo box.
    .AddItem x.DeviceName, y
    y = y + 1
    Next
    .ListIndex = 0
    End With

    End Sub
    [/code]
    Last edited by RedSon; Nov 21 '07, 07:14 PM.
  • creative1
    Contributor
    • Sep 2007
    • 274

    #2
    Good Piece of Work.

    Comment

    • delavegas
      New Member
      • Jan 2015
      • 1

      #3
      Absolute amazin. But there a problem, SendMessage(HWN D_BROADCAST, WM_WININICHANGE , 0&, "windows") in sometimes, crash my aplication. Any tip to resolve this problem?!

      Comment

      Working...