using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace ChuPiao.Common.Utils
{
    public class PrinterPort
    {
        public PrinterPort() 
        { }
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct PORT_INFO_1
        {
            [MarshalAs(UnmanagedType.LPTStr)]
            public string pName;
        }

        [DllImport("WINspool.drv", CharSet = CharSet.Auto)]
        static extern bool EnumPorts(string pName, int level, IntPtr bufptr,
         int cbBuf, out int pcbNeeded, out int pcReturned);



        public List<string> ListPorts()//out ArrayList portslist
        {
            List<string> list = new List<string>();
            int pcReturned = 0;
            int pcbNeeded = 0;
            IntPtr outb = IntPtr.Zero;

            EnumPorts(null, 1, outb, 0, out pcbNeeded, out pcReturned);
            outb = Marshal.AllocHGlobal(pcbNeeded + 1);
            EnumPorts(null, 1, outb, pcbNeeded, out pcbNeeded, out pcReturned);
            PORT_INFO_1[] portsArray = new PORT_INFO_1[pcReturned];

            IntPtr current = outb;
            for (int i = 0; i < pcReturned; i++)
            {
                portsArray[i] = (PORT_INFO_1)Marshal.PtrToStructure(current, typeof(PORT_INFO_1));
                current = (IntPtr)((int)current + Marshal.SizeOf(typeof(PORT_INFO_1)));                
                list.Add(portsArray[i].pName.TrimEnd(':'));               
            }
            Marshal.FreeHGlobal(outb);
            return list;
        }
    }
}
