Adding a printer in VB.NET

I took some time for me before I found out that API AddPrinter can be used to add printer whose driver is already installed. All I wanted to do was to add a Printer if its not present and the driver was built-in Windows XP itself.

First I finished adding the printer in VC++ using MFC Application then I wanted to add it using VB.NET either using Declare Function or DllImport by wrapping it in a dll. Then i had to google for a long time when i last arrived at a code that really worked !!!

Module Printer_Module
'declare the API in VB
Private Declare Function AddPrinter Lib "winspool.drv" Alias "AddPrinterW" _
(ByVal pName As IntPtr, ByVal Level As Int32, _
<MarshalAs(UnmanagedType.LPStruct)> ByVal pPrinter As PRINTER_INFO_2) As Int32

'http://www.vbforums.com/archive/index.php/t-263437.html
'still dont know why PRINTER_INFO_2 is Class instead of a Structure

<StructLayout(LayoutKind.Sequential)> _
Public Class PRINTER_INFO_2
<MarshalAs(UnmanagedType.LPTStr)> Public pServerName As String
<MarshalAs(UnmanagedType.LPTStr)> Public pPrinterName As String
<MarshalAs(UnmanagedType.LPTStr)> Public pShareName As String
<MarshalAs(UnmanagedType.LPTStr)> Public pPortName As String
<MarshalAs(UnmanagedType.LPTStr)> Public pDriverName As String
<MarshalAs(UnmanagedType.LPTStr)> Public pComment As String
Public pDevMode As IntPtr
<MarshalAs(UnmanagedType.LPTStr)> Public pLocation As String
<MarshalAs(UnmanagedType.LPTStr)> Public pSepFile As String
<MarshalAs(UnmanagedType.LPTStr)> Public pPrintProcessor As String
<MarshalAs(UnmanagedType.LPTStr)> Public pDatatype As String
<MarshalAs(UnmanagedType.LPTStr)> Public pParameters As String
Public pSecurityDescriptor As IntPtr
Public Attributes As Integer
Public Priority As Integer
Public DefaultPriority As Integer
Public StartTime As Integer
Public UntilTime As Integer
End Class

Function AddMyPrinter() As Boolean

Dim PI2 As New PRINTER_INFO_2()
'only printer name, driver name, port name and print processor need to be filled
With PI2
.pServerName = String.Empty
.pPrinterName = "Apple Color LW 12/660 PS"
.pShareName = String.Empty
.pPortName = "FILE:"
.pDriverName = "Apple Color LW 12/660 PS"
.pComment = String.Empty
.pLocation = String.Empty
.pDevMode = 0
.pSepFile = String.Empty
.pPrintProcessor = "WinPrint"
.pDatatype = String.Empty
.pParameters = String.Empty
.pSecurityDescriptor = 0
.Attributes = 0
.Priority = 0
.DefaultPriority = 0
.StartTime = 0
.UntilTime = 0
End With

Dim x As Integer = AddPrinter(IntPtr.Zero, 2, PI2)
If x = 0 Then
MsgBox("Failed !!!")
MsgBox(Err.LastDllError)
End
End If
Return True
End Function

End Module

Comments

Popular posts from this blog

DoTween - The Big Demo

Download Android SDK standalone for offline installation