Exemplo n.º 1
0
        /// <summary>
        /// Gets list of installed printer monitors
        /// </summary>
        /// <returns>A list of installed printer monitors</returns>
        private List <String> GetInstalledMonitors()
        {
            uint pcbNeeded  = 0;
            uint pcReturned = 0;

            if (PrinterMonitorInstallerPInvoke.EnumMonitors(null, 2, IntPtr.Zero, 0, ref pcbNeeded, ref pcReturned))
            {
                //succeeds, but must not, because buffer is zero (too small)!
                throw new Exception("EnumPorts should fail!");
            }

            int lastWin32Error = Marshal.GetLastWin32Error();

            //ERROR_INSUFFICIENT_BUFFER = 122 expected, if not -> Exception
            if (lastWin32Error != 122)
            {
                throw new Win32Exception(lastWin32Error);
            }

            IntPtr pMonitors = Marshal.AllocHGlobal((int)pcbNeeded);

            if (PrinterMonitorInstallerPInvoke.EnumMonitors(null, 2, pMonitors, pcbNeeded, ref pcbNeeded, ref pcReturned))
            {
                IntPtr currentMonitor = pMonitors;
                PrinterMonitorInstallerPInvoke.MONITOR_INFO_2[] minfo = new PrinterMonitorInstallerPInvoke.MONITOR_INFO_2[pcReturned];

                for (int i = 0; i < pcReturned; i++)
                {
                    minfo[i]       = (PrinterMonitorInstallerPInvoke.MONITOR_INFO_2)Marshal.PtrToStructure(currentMonitor, typeof(PrinterMonitorInstallerPInvoke.MONITOR_INFO_2));
                    currentMonitor = (IntPtr)(currentMonitor.ToInt32() + Marshal.SizeOf(typeof(PrinterMonitorInstallerPInvoke.MONITOR_INFO_2)));
                }
                Marshal.FreeHGlobal(pMonitors);

                List <String> result = new List <string>();
                for (int i = 0; i < pcReturned; i++)
                {
                    result.Add(minfo[i].pName);
                }
                return(result);
            }

            throw new Win32Exception(Marshal.GetLastWin32Error());
        }