C # Call Win32API Series 2 Listing Board Shared Printer C # By calling Win32API to implement a very powerful feature, this article will focus on how to enumerate all shared printers in the local area network by calling Win32API implementation. First we look at the definition BOOL EnumPrinters EnumPrinters function (DWORD Flags, // printer object types LPTSTR Name, // name of printer object DWORD Level, // information level LPBYTE pPrinterEnum, // printer information buffer DWORD cbBuf, // size of printer information buffer LPDWORD pcbNeeded, // bytes received or required LPDWORD pcReturned // number of printers enumerated); this has several api return parameters, the most important is the buffer pPrinterEnum referred to in the structure is an array of PRINTER_INFO_N, Here n is changed according to the Level parameter, where we use 1, so the structure used is typef struct _printer_info_1 {dWord Flags; lptstr pdescription; lptstr pName; lptstr pcomment; }printer_info_1
C # To call the API first to introduce a dynamic library, enumprinters are in the dynamic library of Winspool.drv.
Import statement follows [DllImport ( "winspool.drv", CharSet = CharSet.Auto)] is then defined PRINTER_INFO_1 structure [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)] struct PRINTER_INFO_1 {int flags; [MarshalAs (UnmanagedType.LPTStr )] public string pDescription; [MarshalAs (UnmanagedType.LPTStr)] public string pName; [MarshalAs (UnmanagedType.LPTStr)] public string pComment;} good, all the source code as follows: using System; using System.Collections; using System .Runtime.InteropServices; using System.Diagnostics; using System.Drawing.Printing; public class QuickTest {[DllImport ( "winspool.drv", CharSet = CharSet.Auto)] static extern bool EnumPrinters (int flags, string name, int level , IntPtr pPrinterEnum, int cbBuf, out int pcbNeeded, out int pcReturned); private const int PRINTER_ENUM_NETWORK = 0x00000040; private const int PRINTER_ENUM_LOCAL = 0x00000002; private const int PRINTER_ENUM_REMOTE = 0x00000010; [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto) ] Structprinter_info_1 {int flags; [Marshalas (UnmanagedType. LPTStr)] public string pDescription; [MarshalAs (UnmanagedType.LPTStr)] public string pName; [MarshalAs (UnmanagedType.LPTStr)] public string pComment;} public void EnumeratePrintersWin () {bool Success; int cbRequired; int nEntries; IntPtr outb = IntPtr.Zero; Success = EnumPrinters (PRINTER_ENUM_NETWORK | PRINTER_ENUM_LOCAL | PRINTER_ENUM_REMOTE, null, 1, outb, 0, out cbRequired, out nEntries); outb = Marshal.AllocHGlobal (cbRequired); Success = EnumPrinters (PRINTER_ENUM_NETWORK | PRINTER_ENUM_LOCAL | PRINTER_ENUM_REMOTE, null, 1, Outb, Cbrequired, Out Cbrequired, Out Nentries; Printer_info_1 [] PortsArray = New Printer_INFO_1 [CBREQUIRED];
IntPtr current = outb; try {for (int i = 0; i