468,484 Members | 2,096 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Share your developer knowledge by writing an article on Bytes.

Set default printer

sashi
1,754 Expert 1GB
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
Expand|Select|Wrap|Line Numbers
  1. Public Declare Function WriteProfileString Lib "kernel32" Alias "WriteProfileStringA" (ByVal lpszSection As String, ByVal lpszKeyName As String, ByVal lpszString As String) As Long
  2.  
  3. Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
  4.     Public Const HWND_BROADCAST = &HFFFF&
  5.     Public Const WM_WININICHANGE = &H1A 
  6.  
Code
Expand|Select|Wrap|Line Numbers
  1. Public Function SetDefaultPrinter(objPrn As Printer) As Boolean
  2.     Dim x As Long, sztemp As String
  3.     sztemp = objPrn.DeviceName & "," & objPrn.DriverName & "," & objPrn.Port
  4.     x = WriteProfileString("windows", "device", sztemp)
  5.     x = SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0&, "windows")
  6. End Function
  7.  
  8. Private Sub Command1_Click()
  9.     Dim x As Printer
  10.     If MsgBox("Are You Sure Want To Set " & Combo1.Text & " as Default printer ? ", vbYesNo, "Attention") = vbYes Then
  11.  
  12.         For Each x In Printers
  13.             If x.DeviceName = Combo1.Text Then
  14.                 SetDefaultPrinter x
  15.                 Exit Sub
  16.             End If
  17.         Next
  18.  
  19.     End If
  20. End Sub
  21.  
  22. Private Sub Form_Load()
  23.     Dim x As Printer
  24.     Dim y As Integer
  25.     y = 0
  26.  
  27.     With Combo1 'Scan all available printer and put them
  28.         For Each x In Printers 'in To combo box.
  29.             .AddItem x.DeviceName, y
  30.             y = y + 1
  31.         Next
  32.         .ListIndex = 0
  33.     End With
  34.  
  35. End Sub
  36.  
Dec 5 '06 #1
2 15042
creative1
274 100+
Good Piece of Work.
Dec 21 '07 #2
Absolute amazin. But there a problem, SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0&, "windows") in sometimes, crash my aplication. Any tip to resolve this problem?!
Jan 6 '15 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Pablo | last post: by
2 posts views Thread by Willem | last post: by
reply views Thread by Karthick_Microsoft | last post: by
reply views Thread by NPC403 | last post: by
2 posts views Thread by gieforce | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.