全局代码
<FlagsAttribute> _
Public Enum PrinterEnumFlags
PRINTER_ENUM_DEFAULT = &H1
PRINTER_ENUM_LOCAL = &H2
PRINTER_ENUM_CONNECTIONS = &H4
PRINTER_ENUM_FAVORITE = &H4
PRINTER_ENUM_NAME = &H8
PRINTER_ENUM_REMOTE = &H10
PRINTER_ENUM_SHARED = &H20
PRINTER_ENUM_NETWORK = &H40
PRINTER_ENUM_EXPAND = &H4000
PRINTER_ENUM_CONTAINER = &H8000
PRINTER_ENUM_ICONMASK = &Hff0000
PRINTER_ENUM_ICON1 = &H10000
PRINTER_ENUM_ICON2 = &H20000
PRINTER_ENUM_ICON3 = &H40000
PRINTER_ENUM_ICON4 = &H80000
PRINTER_ENUM_ICON5 = &H100000
PRINTER_ENUM_ICON6 = &H200000
PRINTER_ENUM_ICON7 = &H400000
PRINTER_ENUM_ICON8 = &H800000
PRINTER_ENUM_HIDE = &H1000000
End Enum
<StructLayout(LayoutKind.Sequential, CharSet := CharSet.Auto)> _
Public Structure PRINTER_INFO_1
Private flags As Integer
<MarshalAs(UnmanagedType.LPTStr)> _
Public pDescription As String
<MarshalAs(UnmanagedType.LPTStr)> _
Public pName As String
<MarshalAs(UnmanagedType.LPTStr)> _
Public pComment As String
End Structure
<DllImport("winspool.drv", CharSet := CharSet.Auto, SetLastError := True)> _
Public Function EnumPrinters(Flags As PrinterEnumFlags, Name As String, Level As UInteger, pPrinterEnum As IntPtr, cbBuf As UInteger, ByRef pcbNeeded As UInteger, _
ByRef pcReturned As UInteger) As Boolean
End Function
Private Const ERROR_INSUFFICIENT_BUFFER As Integer = 122
Public Function MyEnumPrinters(Flags As PrinterEnumFlags) As PRINTER_INFO_1()
Dim cbNeeded As UInteger = 0
Dim cReturned As UInteger = 0
Dim pPrInfo4 As IntPtr = IntPtr.Zero
Dim size As UInteger = 0
If EnumPrinters(Flags, Nothing, 1, IntPtr.Zero, size, cbNeeded, _
cReturned) Then
Return New PRINTER_INFO_1() {}
End If
If cbNeeded <> 0 Then
pPrInfo4 = Marshal.AllocHGlobal(CInt(cbNeeded) + 128)
size = cbNeeded + 128
EnumPrinters(Flags, Nothing, 1, pPrInfo4, size, cbNeeded, _
cReturned)
If cReturned <> 0 Then
Dim printerInfo1 As PRINTER_INFO_1() = New PRINTER_INFO_1(cReturned - 1) {}
Dim offset As Integer = pPrInfo4.ToInt32()
Dim Type As Type = Gettype(PRINTER_INFO_1)
Dim increment As Integer = Marshal.SizeOf(Type)
For i As Integer = 0 To cReturned - 1
printerInfo1(i) = CType(Marshal.PtrToStructure(New IntPtr(offset), Type), PRINTER_INFO_1)
offset += increment
Next
Marshal.FreeHGlobal(pPrInfo4)
Return printerInfo1
End If
End If
Return New PRINTER_INFO_1() {}
End Function