예제 #1
0
        private IEnumerable <string> EnumerateLocalPrinterNames()
        {
            int    cbneeded = 0;
            int    nents    = 0;
            int    bufsize  = 0;
            IntPtr buf      = IntPtr.Zero;

            PRINTER_INFO_4[] printerinfoarray;
            try
            {
                while (!EnumPrinters(PRINTER_ENUM.LOCAL | PRINTER_ENUM.SHARED, null, 4, buf, bufsize, out cbneeded, out nents))
                {
                    if (cbneeded == bufsize)
                    {
                        throw new InvalidOperationException("Unable to enumerate printers");
                    }

                    if (buf != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(buf);
                    }

                    buf     = Marshal.AllocHGlobal(cbneeded);
                    bufsize = cbneeded;
                }


                printerinfoarray = new PRINTER_INFO_4[nents];

                for (int i = 0; i < nents; i++)
                {
                    printerinfoarray[i] = (PRINTER_INFO_4)Marshal.PtrToStructure(buf + i * Marshal.SizeOf(typeof(PRINTER_INFO_4)), typeof(PRINTER_INFO_4));
                }

                return(printerinfoarray.Select(pi => pi.PrinterName).ToArray());
            }
            finally
            {
                if (buf != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buf);
                }
            }
        }
        private IEnumerable<string> EnumerateLocalPrinterNames()
        {
            int cbneeded = 0;
            int nents = 0;
            int bufsize = 0;
            IntPtr buf = IntPtr.Zero;
            PRINTER_INFO_4[] printerinfoarray;
            try
            {
                while (!EnumPrinters(PRINTER_ENUM.LOCAL | PRINTER_ENUM.SHARED, null, 4, buf, bufsize, out cbneeded, out nents))
                {
                    if (cbneeded == bufsize)
                    {
                        throw new InvalidOperationException("Unable to enumerate printers");
                    }

                    if (buf != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(buf);
                    }

                    buf = Marshal.AllocHGlobal(cbneeded);
                    bufsize = cbneeded;
                }

                printerinfoarray = new PRINTER_INFO_4[nents];

                for (int i = 0; i < nents; i++)
                {
                    printerinfoarray[i] = (PRINTER_INFO_4)Marshal.PtrToStructure(buf + i * Marshal.SizeOf(typeof(PRINTER_INFO_4)), typeof(PRINTER_INFO_4));
                }

                return printerinfoarray.Select(pi => pi.PrinterName).ToArray();
            }
            finally
            {
                if (buf != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(buf);
                }
            }
        }