As part of the install to a project I need to create a Windows printer to print to a file that will then be faxed via a Linux server.

I have worked out that I need to use AddPrinterDriver first and then AddPrinter to create the printer but unfortunately I am a bit of a .NET newbie and can't get the following code for AddPrinter to work - it returns error 87 and the handle is some 16 digits long.

VB Code:
  1. Private Overloads Declare Function AddPrinter Lib "winspool.drv" Alias "AddPrinterA" _
  2.        (ByVal pName As String, ByVal Level As Long, _
  3.        <MarshalAs(UnmanagedType.LPStruct)> ByVal pPrinter As PRINTER_INFO_2) As Long
  4.     Private Overloads Declare Function ClosePrinter Lib "winspool.drv" _
  5.        (ByVal hPrinter As Long) As Long
  6.  
  7.     <StructLayout(LayoutKind.Sequential)> Public Class PRINTER_INFO_2
  8.         Public pServerName As String
  9.         Public pPrinterName As String
  10.         Public pShareName As String
  11.         Public pPortName As String
  12.         Public pDriverName As String
  13.         Public pComment As String
  14.         Public pLocation As String
  15.         Public pDevMode As Long
  16.         Public pSepFile As String
  17.         Public pPrintProcessor As String
  18.         Public pDatatype As String
  19.         Public pParameters As String
  20.         Public pSecurityDescriptor As Long
  21.         Public Attributes As Long
  22.         Public Priority As Long
  23.         Public DefaultPriority As Long
  24.         Public StartTime As Long
  25.         Public UntilTime As Long
  26.     End Class
  27.  
  28.     Function CreatePrinter(ByVal strPrinter As String, ByVal strPort As String, _
  29.       ByVal strDriver As String) As Boolean
  30.         Dim hPrinter As Long
  31.         Dim PI2 As New PRINTER_INFO_2()
  32.  
  33.         With PI2
  34.             .pServerName = ""
  35.             .pPrinterName = strPrinter
  36.             .pShareName = ""
  37.             .pPortName = strPort
  38.             .pDriverName = strDriver
  39.             .pComment = ""
  40.             .pLocation = ""
  41.             .pDevMode = 0
  42.             .pSepFile = ""
  43.             .pPrintProcessor = "WinPrint"
  44.             .pDatatype = ""
  45.             .pParameters = ""
  46.             .pSecurityDescriptor = 0
  47.             .Attributes = 0
  48.             .Priority = 0
  49.             .DefaultPriority = 0
  50.             .StartTime = 0
  51.             .UntilTime = 0
  52.         End With
  53.  
  54.         hPrinter = AddPrinter("", 2, PI2)
  55.         If hPrinter <> 0 Then
  56.             ClosePrinter(hPrinter)
  57.             CreatePrinter = True
  58.         Else
  59.             CreatePrinter = False
  60.         End If
  61.     End Function

Any ideas on how to fix it?

chalkster