By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,345 Members | 2,404 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Set default printer

sashi
Expert 100+
P: 1,754
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
Share this Article
Share on Google+
2 Comments


100+
P: 274
Good Piece of Work.
Dec 21 '07 #2

P: 1
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