public Printer Get(string name, string model, PrinterTypes type) { switch (type) { case PrinterTypes.Canon: return(new Canon(name, model)); case PrinterTypes.Epson: return(new Epson(name, model)); default: throw new InvalidOperationException("instance not found"); } }
public static PrinterDevice[] GetPrinters(PrinterTypes printerTypes) { PrinterEnumFlags flags = 0; if ((printerTypes & PrinterTypes.Local) == PrinterTypes.Local) { flags |= PrinterEnumFlags.PRINTER_ENUM_LOCAL; } if ((printerTypes & PrinterTypes.Remote) == PrinterTypes.Remote) { flags |= PrinterEnumFlags.PRINTER_ENUM_REMOTE; } uint cbNeeded = 0; uint cReturned = 0; if (PrinterDevice.EnumPrinters((uint)flags, null, 2, IntPtr.Zero, 0, ref cbNeeded, ref cReturned)) { if (cbNeeded == 0) { return(new PrinterDevice[0]); } } int errorCode = WindowsApi.GetLastErrorCode(); if (errorCode == (int)WindowsError.ErrorInsufficientBuffer) { IntPtr pAddr = IntPtr.Zero; try { pAddr = Marshal.AllocHGlobal((int)cbNeeded); if (PrinterDevice.EnumPrinters((uint)flags, null, 2, pAddr, cbNeeded, ref cbNeeded, ref cReturned)) { PRINTER_INFO_2[] printerInfo = new PRINTER_INFO_2[cReturned]; long address = pAddr.ToInt64(); long addressIncrement = Marshal.SizeOf(typeof(PRINTER_INFO_2)); for (int i1 = 0; i1 < cReturned; i1++) { printerInfo[i1] = (PRINTER_INFO_2)Marshal.PtrToStructure(new IntPtr(address), typeof(PRINTER_INFO_2)); address += addressIncrement; } return((from x in printerInfo select new PrinterDevice(x)).ToArray()); } errorCode = WindowsApi.GetLastErrorCode(); } finally { if (pAddr != IntPtr.Zero) { Marshal.FreeHGlobal(pAddr); } } } string errorMessage = WindowsApi.GetErrorMessage(errorCode); throw new Win32Exception(errorCode, errorMessage); }