Exemple #1
0
        /// <summary>
        /// Creates a System.Drawing.Bitmap image from a WPF source.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static Bitmap MakeBitmapFromWPF(System.Windows.Media.Imaging.BitmapSource source)
        {
            var    mm  = new MemPtr();
            Bitmap bmp = null;

            if (System.Windows.Application.Current is object)
            {
                System.Windows.Application.Current.Dispatcher.Invoke(() =>
                {
                    bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    mm.Alloc(bmp.Width * bmp.Height * 4);
                    var bm    = new System.Drawing.Imaging.BitmapData();
                    bm.Scan0  = mm.Handle;
                    bm.Stride = bmp.Width * 4;
                    bm        = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite | System.Drawing.Imaging.ImageLockMode.UserInputBuffer, System.Drawing.Imaging.PixelFormat.Format32bppArgb, bm);
                    source.CopyPixels(System.Windows.Int32Rect.Empty, mm.Handle, (int)mm.Length, bmp.Width * 4);
                    bmp.UnlockBits(bm);
                    mm.Free();
                });
            }
            else
            {
                bmp = new Bitmap(source.PixelWidth, source.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                mm.Alloc(bmp.Width * bmp.Height * 4);
                var bm = new System.Drawing.Imaging.BitmapData();
                bm.Scan0  = mm.Handle;
                bm.Stride = bmp.Width * 4;
                bm        = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite | System.Drawing.Imaging.ImageLockMode.UserInputBuffer, System.Drawing.Imaging.PixelFormat.Format32bppArgb, bm);
                source.CopyPixels(System.Windows.Int32Rect.Empty, mm.Handle, (int)mm.Length, bmp.Width * 4);
                bmp.UnlockBits(bm);
                mm.Free();
            }

            return(bmp);
        }
Exemple #2
0
        /// <summary>
        /// Retrieves a feature from the device.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="code"></param>
        /// <param name="datalen"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static HIDFeatureResult GetHIDFeature(IntPtr device, int code, int datalen = 16)
        {
            HIDFeatureResult GetHIDFeatureRet = default;
            MemPtr           mm = new MemPtr();

            int i = code;

            try
            {
                mm.AllocZero(datalen);
                mm.ByteAt(0L) = (byte)i;
                if (UsbLibHelpers.HidD_GetFeature(device, mm.Handle, (int)mm.Length))
                {
                    GetHIDFeatureRet = new HIDFeatureResult(i, mm);
                }
                else
                {
                    GetHIDFeatureRet = null;
                }

                mm.Free();
            }
            catch
            {
                mm.Free();
                return(null);
            }

            return(GetHIDFeatureRet);
        }
Exemple #3
0
        /// <summary>
        /// Get volume disk extents for volumes that may or may not span more than one physical drive.
        /// </summary>
        /// <param name="devicePath">The device path of the volume.</param>
        /// <returns>An array of DiskExtent structures.</returns>
        /// <remarks></remarks>
        public static DiskExtent[] GetDiskExtentsFor(string devicePath)
        {
            DiskExtent[] deOut  = null;
            MemPtr       inBuff = new MemPtr();
            int          inSize;
            IntPtr       file;
            int          h  = 0;
            var          de = new DISK_EXTENT();
            var          ve = new VOLUME_DISK_EXTENTS();
            bool         r;

            file = IO.CreateFile(devicePath, IO.GENERIC_READ, IO.FILE_SHARE_READ | IO.FILE_SHARE_WRITE, IntPtr.Zero, IO.OPEN_EXISTING, IO.FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
            if (file == DevProp.INVALID_HANDLE_VALUE)
            {
                return(null);
            }

            uint arb = 0;

            inSize        = Marshal.SizeOf(de) + Marshal.SizeOf(ve);
            inBuff.Length = inSize;
            r             = DeviceIoControl(file, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, inBuff, (uint)inSize, ref arb, IntPtr.Zero);

            if (!r && User32.GetLastError() == ERROR_MORE_DATA)
            {
                inBuff.Length = inSize * inBuff.IntAt(0L);
                r             = DeviceIoControl(file, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, IntPtr.Zero, 0, inBuff, (uint)inSize, ref arb, IntPtr.Zero);
            }

            if (!r)
            {
                inBuff.Free();
                User32.CloseHandle(file);
                return(null);
            }

            User32.CloseHandle(file);
            ve = VOLUME_DISK_EXTENTS.FromPtr(inBuff);
            inBuff.Free();
            h     = 0;
            deOut = new DiskExtent[ve.Extents.Length];
            foreach (var currentDe in ve.Extents)
            {
                de = currentDe;
                deOut[h].PhysicalDevice = de.DiskNumber;
                deOut[h].Space          = de.Space;
                deOut[h].Size           = de.ExtentLength;
                deOut[h].Offset         = de.StartingOffset;
                h += 1;
            }

            return(deOut);
        }
Exemple #4
0
        public static string[] GetPhysicalMonitorNames(IntPtr hMonitor)
        {
            var mm = new MemPtr();

            string[]         sOut = null;
            PHYSICAL_MONITOR pm;

            uint nmon = 0;

            if (!GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, out nmon))
            {
                return(null);
            }

            int cb   = Marshal.SizeOf <PHYSICAL_MONITOR>();
            int size = cb * (int)nmon;

            mm.Alloc(size);

            try
            {
                if (GetPhysicalMonitorsFromHMONITOR(hMonitor, size, mm))
                {
                    sOut = new string[size];
                    int i;

                    for (i = 0; i < nmon; i++)
                    {
                        pm      = mm.ToStructAt <PHYSICAL_MONITOR>(i * cb);
                        sOut[i] = pm.szPhysicalMonitorDescription;
                    }

                    DestroyPhysicalMonitors((uint)size, mm);
                }
                else
                {
                    sOut = new string[] { NativeErrorMethods.FormatLastError() };
                }

                mm.Free();
            }
            catch
            {
                mm.Free();
            }

            return(sOut);
        }
Exemple #5
0
        /// <summary>
        /// Returns the short value of a Hid feature code.
        /// </summary>
        /// <param name="featureCode">The Hid feature code to retrieve.</param>
        /// <param name="result">Receives the result of the operation.</param>
        /// <returns>True if successful.</returns>
        /// <remarks></remarks>
        public bool HidGetFeature(byte featureCode, ref short result)
        {
            bool HidGetFeatureRet = default;
            var  hfile            = HidFeatures.OpenHid(this);

            if (hfile == IntPtr.Zero)
            {
                return(false);
            }
            var mm = new MemPtr();

            mm.Alloc(3L);
            mm.ByteAt(0L) = featureCode;
            if (!UsbLibHelpers.HidD_GetFeature(hfile, mm, 3))
            {
                HidGetFeatureRet = false;
            }
            else
            {
                HidGetFeatureRet = true;
                result           = mm.ShortAtAbsolute(1L);
            }

            mm.Free();
            HidFeatures.CloseHid(hfile);
            return(HidGetFeatureRet);
        }
Exemple #6
0
        /// <summary>
        /// Returns the raw byte data for a Hid feature code.
        /// </summary>
        /// <param name="featureCode">The Hid feature code to retrieve.</param>
        /// <param name="result">Receives the result of the operation.</param>
        /// <param name="expectedSize">The expected size, in bytes, of the result.</param>
        /// <returns>True if successful.</returns>
        /// <remarks></remarks>
        public bool HidGetFeature(byte featureCode, ref byte[] result, int expectedSize)
        {
            bool HidGetFeatureRet = default;
            var  hfile            = HidFeatures.OpenHid(this);

            if (hfile == IntPtr.Zero)
            {
                return(false);
            }
            var mm = new MemPtr();

            mm.Alloc(expectedSize + 1);
            mm.ByteAt(0L) = featureCode;
            if (!UsbLibHelpers.HidD_GetFeature(hfile, mm, expectedSize))
            {
                HidGetFeatureRet = false;
            }
            else
            {
                HidGetFeatureRet = true;
                result           = mm.ToByteArray(1L, expectedSize);
            }

            HidFeatures.CloseHid(hfile);
            mm.Free();
            return(HidGetFeatureRet);
        }
Exemple #7
0
        /// <summary>
        /// Sets the long value of a Hid feature code.
        /// </summary>
        /// <param name="featureCode">The Hid feature code to set.</param>
        /// <param name="value">The value to set.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public bool HidSetFeature(byte featureCode, long value)
        {
            bool HidSetFeatureRet = default;
            var  hfile            = HidFeatures.OpenHid(this);

            if (hfile == IntPtr.Zero)
            {
                return(false);
            }
            var mm = new MemPtr();

            mm.Alloc(9L);
            mm.ByteAt(0L)         = featureCode;
            mm.LongAtAbsolute(1L) = value;
            if (!UsbLibHelpers.HidD_SetFeature(hfile, mm, 9))
            {
                HidSetFeatureRet = false;
            }
            else
            {
                HidSetFeatureRet = true;
            }

            HidFeatures.CloseHid(hfile);
            mm.Free();
            return(HidSetFeatureRet);
        }
Exemple #8
0
        /// <summary>
        /// Sets the raw byte value of a Hid feature code.
        /// </summary>
        /// <param name="featureCode">The Hid feature code to set.</param>
        /// <param name="value">The value to set.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public bool HidSetFeature(byte featureCode, byte[] value)
        {
            bool HidSetFeatureRet = default;
            var  hfile            = HidFeatures.OpenHid(this);

            if (hfile == IntPtr.Zero)
            {
                return(false);
            }
            var mm = new MemPtr();

            mm.Alloc(value.Length + 1);
            mm.FromByteArray(value, 1L);
            mm.ByteAt(0L) = featureCode;
            if (!UsbLibHelpers.HidD_SetFeature(hfile, mm, (int)mm.Length))
            {
                HidSetFeatureRet = false;
            }
            else
            {
                HidSetFeatureRet = true;
            }

            mm.Free();
            HidFeatures.CloseHid(hfile);
            return(HidSetFeatureRet);
        }
        private bool disposedValue; // To detect redundant calls
        //private bool shuttingDown;

        /// <summary>
        /// Dispose of the managed and unmanaged resources.
        /// </summary>
        /// <param name="disposing"></param>
        /// <remarks></remarks>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                //shuttingDown = true;
                if (_isWatching)
                {
                    StopWatching();
                }
                _lastIndex = 0;
                _WaitList  = null;
                _WaitLock  = 0;

                // destroy the window handle
                DestroyHandle();

                // free the buffer
                _Buff.Free(true);

                // release the String handle
                _stor = null;
            }

            disposedValue = true;
            //shuttingDown = false;
        }
Exemple #10
0
        /// <summary>
        /// Get all mount points for a volume.
        /// </summary>
        /// <param name="path">Volume Guid Path.</param>
        /// <returns>An array of strings that represent mount points.</returns>
        /// <remarks></remarks>
        public static string[] GetVolumePaths(string path)
        {
            string[] GetVolumePathsRet = default;
            int      cc   = 1024;
            int      retc = 0;
            var      mm   = new MemPtr();
            bool     r;

            mm.Alloc(cc);

            r = NativeDisk.GetVolumePathNamesForVolumeName(path, mm.Handle, cc, ref retc);
            if (!r)
            {
                return(null);
            }
            if (retc > 1024)
            {
                mm.ReAlloc(retc);
                r = NativeDisk.GetVolumePathNamesForVolumeName(path, mm, retc, ref retc);
            }

            GetVolumePathsRet = mm.GetStringArray(0L);
            mm.Free();
            return(GetVolumePathsRet);
        }
Exemple #11
0
        /// <summary>
        /// Retrieves a linked, unmanaged structure array of IP_ADAPTER_ADDRESSES, enumerating all network interfaces on the system.
        /// This function is internal to the managed API in this assembly and is not intended to be used independently from it.
        /// The results of this function are abstracted into the managed <see cref="AdaptersCollection" /> class. Use that, instead.
        /// </summary>
        /// <param name="origPtr">Receives the memory pointer for the memory allocated to retrieve the information from the system.</param>
        /// <param name="noRelease">Specifies that the memory will not be released after usage (this is a typical scenario).</param>
        /// <returns>A linked, unmanaged structure array of IP_ADAPTER_ADDRESSES.</returns>
        /// <remarks></remarks>
        internal static IP_ADAPTER_ADDRESSES[] GetAdapters(ref MemPtr origPtr, bool noRelease = true)
        {
            var lpadapt = new LPIP_ADAPTER_ADDRESSES();
            IP_ADAPTER_ADDRESSES adapt;

            uint cblen = 0;

            var res = GetAdaptersAddresses(AfENUM.AfUnspecified, GAA_FLAGS.GAA_FLAG_INCLUDE_GATEWAYS | GAA_FLAGS.GAA_FLAG_INCLUDE_WINS_INFO | GAA_FLAGS.GAA_FLAG_INCLUDE_ALL_COMPARTMENTS | GAA_FLAGS.GAA_FLAG_INCLUDE_ALL_INTERFACES, IntPtr.Zero, lpadapt, ref cblen);

            // we have a buffer overflow?  We need to get more memory.
            if (res == ADAPTER_ENUM_RESULT.ERROR_BUFFER_OVERFLOW)
            {
                lpadapt.Handle.Alloc(cblen, noRelease);
                res = GetAdaptersAddresses(AfENUM.AfUnspecified, GAA_FLAGS.GAA_FLAG_INCLUDE_GATEWAYS | GAA_FLAGS.GAA_FLAG_INCLUDE_WINS_INFO, IntPtr.Zero, lpadapt, ref cblen);
            }

            if (res != ADAPTER_ENUM_RESULT.NO_ERROR)
            {
                lpadapt.Dispose();
                throw new NativeException();
            }

            origPtr = lpadapt.Handle;
            IP_ADAPTER_ADDRESSES[] adapters = null;

            int c  = 0;
            int cc = 0;

            adapt = lpadapt;

            do
            {
                if (string.IsNullOrEmpty(adapt.Description) | adapt.FirstDnsServerAddress.Handle == IntPtr.Zero)
                {
                    c    += 1;
                    adapt = adapt.Next;
                    if (adapt.Next.Handle == MemPtr.Empty)
                    {
                        break;
                    }
                    continue;
                }

                Array.Resize(ref adapters, cc + 1);
                adapters[cc] = adapt;
                adapt        = adapt.Next;
                cc          += 1;
                c           += 1;
            }while (adapt.Next.Handle != MemPtr.Empty);

            // there is currently no reason for this function to free this pointer,
            // but we reserve the right to do so, in the future.
            if (!noRelease)
            {
                origPtr.Free();
            }

            return(adapters);
        }
Exemple #12
0
        protected void Free()
        {
            if (_origPtr.Handle != IntPtr.Zero)
            {
                _origPtr.Free(true);
            }

            _Adapters = null;
            _Col.Clear();
        }
Exemple #13
0
            /// <summary>
            /// Validate the header and CRC-32 of this structure.
            /// </summary>
            /// <returns>True if the structure is valid.</returns>
            /// <remarks></remarks>
            public bool Validate()
            {
                bool ValidateRet = default;
                var  mm          = new MemPtr();

                mm.FromStruct(this);
                mm.UIntAt(4L) = 0U;

                // validate the crc and the signature moniker
                ValidateRet = HeaderCRC32 == mm.CalculateCrc32() && Signature == 0x5452415020494645;
                mm.Free();
                return(ValidateRet);
            }
Exemple #14
0
        public static bool GetVolumePathNamesForVolumeName(string lpszVolumeName, ref string[] lpszVolumePathNames)
        {
            var  sp = new MemPtr();
            uint ul = 0U;

            IO.GetVolumePathNamesForVolumeNameW(lpszVolumeName, IntPtr.Zero, 0U, ref ul);

            sp.Alloc((ul + 1L) * sizeof(char));

            IO.GetVolumePathNamesForVolumeNameW(lpszVolumeName, sp, (uint)sp.Length, ref ul);
            lpszVolumePathNames = sp.GetStringArray(0L);
            sp.Free();

            return(true);
        }
Exemple #15
0
        public static NETRESOURCE[] EnumComputer(string computer, string username = null, string password = null)
        {
            NETRESOURCE[] EnumComputerRet = default;
            var           lpnet           = new NETRESOURCE();
            MemPtr        mm = new MemPtr();

            if (computer.Substring(0, 2) == @"\\")
            {
                computer = computer.Substring(2);
            }

            mm.ReAlloc(10240L);

            if (username is object && password is object)
            {
                lpnet.lpRemoteName = @"\\" + computer;
                Marshal.StructureToPtr(lpnet, mm.Handle, false);
                int res = LocalNet.WNetAddConnection3(IntPtr.Zero, mm.Handle, password, username, CONNECT_INTERACTIVE);
                mm.Free();
                if (res != 0)
                {
                    return(null);
                }

                mm.ReAlloc(10240L);
            }

            lpnet.dwDisplayType = RESOURCEDISPLAYTYPE_SERVER;
            lpnet.lpRemoteName  = @"\\" + computer;
            lpnet.dwScope       = RESOURCE_CONTEXT;
            lpnet.dwUsage       = RESOURCEUSAGE_CONTAINER;
            Marshal.StructureToPtr(lpnet, mm.Handle, false);
            EnumComputerRet = DoEnum(mm.Handle);
            mm.Free();
            return(EnumComputerRet);
        }
Exemple #16
0
        public static NETRESOURCE[] DoEnum(IntPtr lpNet)
        {
            NETRESOURCE[] DoEnumRet = default;
            MemPtr        mm        = new MemPtr();
            int           cb        = 10240;

            NETRESOURCE[] bb    = null;
            NETRESOURCE[] nin   = null;
            IntPtr        hEnum = IntPtr.Zero;
            int           e     = 0;

            e = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, RESOURCEUSAGE_ALL, lpNet, ref hEnum);
            if (e != NO_ERROR)
            {
                return(null);
            }

            e = 0;
            mm.ReAlloc(10240L);
            int arglpcCount = 1;

            while (WNetEnumResource(hEnum, ref arglpcCount, mm, ref cb) == NO_ERROR)
            {
                Array.Resize(ref bb, e + 1);
                nin   = DoEnum(mm.Handle);
                bb[e] = mm.ToStruct <NETRESOURCE>();
                if (nin is object)
                {
                    bb  = WNACat(bb, nin);
                    nin = null;
                }

                if (bb is object)
                {
                    e = bb.Length;
                }
                else
                {
                    e = 0;
                }
            }

            mm.Free();
            WNetCloseEnum(hEnum);
            DoEnumRet = bb;
            return(DoEnumRet);
        }
Exemple #17
0
        /// <summary>
        /// Mount the virtual drive, permanently.  The virtual drive will stay mounted beyond the lifetime of this instance.
        /// </summary>
        /// <param name="makePermanent"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public bool Attach(bool makePermanent)
        {
            if (_Handle == IntPtr.Zero || Attached)
            {
                return(false);
            }

            var mm = new MemPtr(8L);

            mm.ByteAt(0L) = 1;

            uint r = VirtDisk.AttachVirtualDisk(_Handle, IntPtr.Zero, makePermanent ? ATTACH_VIRTUAL_DISK_FLAG.ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME : ATTACH_VIRTUAL_DISK_FLAG.ATTACH_VIRTUAL_DISK_FLAG_NONE, 0U, mm.Handle, IntPtr.Zero);

            mm.Free();

            return(r == 0L);
        }
Exemple #18
0
        /// <summary>
        /// Retrieves the disk geometry of the specified disk.
        /// </summary>
        /// <param name="hfile">Handle to a valid, open disk.</param>
        /// <param name="geo">Receives the disk geometry information.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool DiskGeometry(IntPtr hfile, ref DISK_GEOMETRY_EX geo)
        {
            if (hfile == DevProp.INVALID_HANDLE_VALUE)
            {
                return(false);
            }
            MemPtr mm = new MemPtr();
            uint   l  = 0U;
            uint   cb = 0U;

            l = (uint)Marshal.SizeOf <DISK_GEOMETRY_EX>();
            mm.Alloc(l);
            NativeDisk.DeviceIoControl(hfile, NativeDisk.IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, IntPtr.Zero, 0, mm.Handle, l, ref cb, IntPtr.Zero);
            geo = mm.ToStruct <DISK_GEOMETRY_EX>();
            mm.Free();
            return(true);
        }
Exemple #19
0
        /// <summary>
        /// Gray out an icon.
        /// </summary>
        /// <param name="icn">The input icon.</param>
        /// <returns>The grayed out icon.</returns>
        /// <remarks></remarks>
        public static Image GrayIcon(Icon icn)
        {
            var n = new Bitmap(icn.Width, icn.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            var g = System.Drawing.Graphics.FromImage(n);

            g.FillRectangle(Brushes.Transparent, new Rectangle(0, 0, n.Width, n.Height));
            g.DrawIcon(icn, 0, 0);
            g.Dispose();
            var bm = new System.Drawing.Imaging.BitmapData();
            var mm = new MemPtr(n.Width * n.Height * 4);

            bm.Stride      = n.Width * 4;
            bm.Scan0       = mm;
            bm.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb;
            bm.Width       = n.Width;
            bm.Height      = n.Height;
            bm             = n.LockBits(new Rectangle(0, 0, n.Width, n.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite | System.Drawing.Imaging.ImageLockMode.UserInputBuffer, System.Drawing.Imaging.PixelFormat.Format32bppArgb, bm);
            int i;
            int c;

            // Dim b() As Byte

            // ReDim b((bm.Stride * bm.Height) - 1)
            // MemCpy(b, bm.Scan0, bm.Stride * bm.Height)
            c = bm.Stride * bm.Height - 1;
            int stp = (int)(bm.Stride / (double)bm.Width);

            // For i = 3 To c Step stp
            // If b(i) > &H7F Then b(i) = &H7F
            // Next

            for (i = 3; stp >= 0 ? i <= c : i >= c; i += stp)
            {
                if (mm.ByteAt(i) > 0x7F)
                {
                    mm.ByteAt(i) = 0x7F;
                }
            }

            // MemCpy(bm.Scan0, b, bm.Stride * bm.Height)
            n.UnlockBits(bm);
            mm.Free();
            return(n);
        }
Exemple #20
0
        /// <summary>
        /// Return the username for the current user
        /// </summary>
        /// <returns></returns>
        public static string CurrentUserName()
        {
            string CurrentUserNameRet = default;
            MemPtr lps = new MemPtr();
            int    cb  = 10240;

            lps.ReAlloc(10240L);
            lps.ZeroMemory();
            if (GetUserName(lps.Handle, ref cb))
            {
                CurrentUserNameRet = lps.ToString();
            }
            else
            {
                CurrentUserNameRet = null;
            }

            lps.Free();
            return(CurrentUserNameRet);
        }
Exemple #21
0
        /// <summary>
        /// Return the current user's full display name
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string CurrentUserFullName(ExtendedNameFormat type = ExtendedNameFormat.NameDisplay)
        {
            string CurrentUserFullNameRet = default;
            MemPtr lps;
            int    cb = 10240;

            lps = new MemPtr(10240L);
            lps.ZeroMemory();

            if (GetUserNameEx(type, lps.Handle, ref cb))
            {
                CurrentUserFullNameRet = lps.ToString();
            }
            else
            {
                CurrentUserFullNameRet = null;
            }

            lps.Free();
            return(CurrentUserFullNameRet);
        }
Exemple #22
0
        public static IntPtr DoRegisterDeviceClassNotification(IntPtr hWnd, Guid devclass)
        {
            var mm = new MemPtr();

            var bh = new DEV_BROADCAST_HDR();
            var di = new DEV_BROADCAST_DEVICEINTERFACE();

            bh.dbch_size = Marshal.SizeOf <DEV_BROADCAST_HDR>();
            di.dbcc_size = Marshal.SizeOf <DEV_BROADCAST_DEVICEINTERFACE>();

            bh.dbch_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
            di.dbcc_classguid  = devclass;

            mm.Alloc(bh.dbch_size + di.dbcc_size);

            mm.FromStruct(bh);
            mm.FromStructAt(bh.dbch_size, di);

            var ret = RegisterDeviceNotification(hWnd, mm, DEVICE_NOTIFY_WINDOW_HANDLE);

            mm.Free();

            return(ret);
        }
Exemple #23
0
        /// <summary>
        /// Enumerate all display monitors.
        /// </summary>
        /// <returns>An array of PrinterDeviceInfo objects.</returns>
        /// <remarks></remarks>
        public static MonitorDeviceInfo[] EnumMonitors()
        {
            var minf = _internalEnumerateDevices <MonitorDeviceInfo>(DevProp.GUID_DEVINTERFACE_MONITOR, ClassDevFlags.DeviceInterface | ClassDevFlags.Present);
            var mon  = new Monitors();

            DISPLAY_DEVICE dd;

            dd.cb = (uint)Marshal.SizeOf <DISPLAY_DEVICE>();
            var mm = new MemPtr();

            mm.Alloc(dd.cb);
            mm.UIntAt(0) = dd.cb;

            if (minf is object && minf.Count() > 0)
            {
                foreach (var x in minf)
                {
                    foreach (var y in mon)
                    {
                        if (MultiMon.EnumDisplayDevices(y.DevicePath, 0, mm, MultiMon.EDD_GET_DEVICE_INTERFACE_NAME))
                        {
                            dd = mm.ToStruct <DISPLAY_DEVICE>();
                            DEVMODE dev = new DEVMODE();

                            dev.dmSize        = (ushort)Marshal.SizeOf <DEVMODE>();
                            dev.dmDriverExtra = 0;

                            var mm2 = new MemPtr(65535 + dev.dmSize);



                            var b = MultiMon.EnumDisplaySettingsEx(y.DevicePath, 0xffffffff, ref dev, 0);
                            if (!b)
                            {
                                var s = NativeErrorMethods.FormatLastError();
                            }


                            mm2.Free();

                            if (dd.DeviceID.ToUpper() == x.DevicePath.ToUpper())
                            {
                                x.Source = y;
                                break;
                            }
                        }
                    }
                }
            }

            mm.Free();

            if (minf is null)
            {
                return(null);
            }

            Array.Sort(minf, new Comparison <MonitorDeviceInfo>((x, y) => { if (x.FriendlyName is object && y.FriendlyName is object)
                                                                            {
                                                                                return(string.Compare(x.FriendlyName, y.FriendlyName));
                                                                            }
                                                                            else
                                                                            {
                                                                                return(string.Compare(x.Description, y.Description));
                                                                            } }));
            return(minf);
        }
Exemple #24
0
        public void Refresh()
        {
            var nad  = new Dictionary <int, NetworkAdapter>();
            var lOut = new List <NetworkAdapter>();

            var newmm = new MemPtr();

            // Get the array of unmanaged IP_ADAPTER_ADDRESSES structures
            var newads = IfDefApi.GetAdapters(ref newmm, true);

            var di    = DeviceEnum.EnumerateNetworkDevices();
            var iftab = IfTable.GetIfTable();

            foreach (var adap in newads)
            {
                var newp = new NetworkAdapter(adap);
                foreach (var de in di)
                {
                    if ((de.Description ?? "") == (adap.Description ?? "") || (de.FriendlyName ?? "") == (adap.FriendlyName ?? "") || (de.FriendlyName ?? "") == (adap.Description ?? "") || (de.Description ?? "") == (adap.FriendlyName ?? ""))
                    {
                        newp.DeviceInfo = de;

                        foreach (var iface in iftab)
                        {
                            if (newp.PhysicalAddress == iface.bPhysAddr)
                            {
                                newp.PhysIfaceInternal.Add(iface);
                            }
                        }

                        nad.Add(newp.IfIndex, newp);
                        _ = Task.Run(() => PopulateInternetStatus(newp));

                        break;
                    }
                }
            }

            if (adapters == null)
            {
                adapters = new ObservableCollection <NetworkAdapter>();
            }

            if (adapters.Count == 0)
            {
                foreach (var kv in nad)
                {
                    adapters.Add(kv.Value);
                }
            }
            else
            {
                var kseen = new List <int>();

                int c = adapters.Count - 1;
                int i;

                for (i = c; i >= 0; i--)
                {
                    if (nad.ContainsKey(adapters[i].IfIndex))
                    {
                        adapters[i].AssignNewNativeObject(nad[adapters[i].IfIndex]);
                        kseen.Add(adapters[i].IfIndex);
                    }
                    else
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            adapters.RemoveAt(i);
                        });
                    }
                }

                foreach (var kv in nad)
                {
                    if (!kseen.Contains(kv.Value.IfIndex))
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            adapters.Add(kv.Value);
                        });
                    }
                }
            }

            if (_origPtr != MemPtr.Empty)
            {
                _origPtr.Free(true);
            }

            _origPtr = newmm;

            QuickSort.Sort(adapters, new Comparison <NetworkAdapter>((a, b) => a.IfIndex - b.IfIndex));
        }
Exemple #25
0
        private void AssignNewNativeObject(IP_ADAPTER_ADDRESSES nativeObject, bool noCreateIcon = false)
        {
            // Store the native object.
            Source = nativeObject;

            if (!noCreateIcon)
            {
                // First thing's first... let's get the icon for the object from its parsing name.
                // Which is magically the parsing name of the network device list and the adapter's GUID name.
                string s  = @"::{7007ACC7-3202-11D1-AAD2-00805FC1270E}\" + AdapterName;
                var    mm = new MemPtr();

                NativeShell.SHParseDisplayName(s, IntPtr.Zero, out mm.handle, 0, out _);

                if (mm.Handle != IntPtr.Zero)
                {
                    // Get a WPFImage

                    // string library = @"%systemroot%\system32\shell32.dll"


                    if (OperStatus == IF_OPER_STATUS.IfOperStatusUp)
                    {
                        //if (HasInternet == InternetStatus.HasInternet)
                        //{
                        //    var icn = Resources.LoadLibraryIcon(Environment.ExpandEnvironmentVariables(@"%systemroot%\system32\netcenter.dll") + ",2", StandardIcons.Icon16);
                        //    var icn2 = Resources.GetItemIcon(mm, Resources.SystemIconSizes.ExtraLarge);

                        //    var bmp = new System.Drawing.Bitmap(icn2.Width, icn2.Height,  System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                        //    var g = System.Drawing.Graphics.FromImage(bmp);

                        //    g.DrawIcon(icn2, 0, 0);
                        //    g.DrawIcon(icn, 0, icn2.Height - 16);

                        //    g.Dispose();

                        //    _Icon = Resources.MakeWPFImage(bmp);
                        //    bmp.Dispose();
                        //    icn.Dispose();
                        //    icn2.Dispose();
                        //}
                        //else
                        //{


                        _Icon = Resources.MakeWPFImage(Resources.GetItemIcon(mm, Resources.SystemIconSizes.ExtraLarge));

                        //}
                    }
                    else
                    {
                        _Icon = Resources.MakeWPFImage((System.Drawing.Bitmap)Resources.GrayIcon(Resources.GetItemIcon(mm, Resources.SystemIconSizes.ExtraLarge)));
                    }
                    mm.Free();

                    _canShowNet = true;
                }
                else
                {
                    _canShowNet = false;
                }
            }

            OnPropertyChanged(nameof(ReceiveLinkSpeed));
            OnPropertyChanged(nameof(TransmitLinkSpeed));
            OnPropertyChanged(nameof(OperStatus));

            foreach (var pr in allProps)
            {
                if (pr.Name.Contains("Address"))
                {
                    OnPropertyChanged(pr.Name);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Retrieve the partition table of a GPT-layout disk, manually.
        /// Must be Administrator.
        /// </summary>
        /// <param name="inf">DiskDeviceInfo object to the physical disk to read.</param>
        /// <param name="gptInfo">Receives the drive layout information.</param>
        /// <returns>True if successful.</returns>
        /// <remarks></remarks>
        public static bool ReadRawGptDisk(string devicePath, ref RAW_GPT_DISK gptInfo)
        {
            // Demand Administrator for accessing a raw disk.
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            // Dim principalPerm As New PrincipalPermission(Nothing, "Administrators")
            // principalPerm.Demand()


            var hfile = IO.CreateFile(devicePath, IO.GENERIC_READ | IO.GENERIC_WRITE, IO.FILE_SHARE_READ | IO.FILE_SHARE_WRITE, IntPtr.Zero, IO.OPEN_EXISTING, IO.FILE_FLAG_NO_BUFFERING | IO.FILE_FLAG_RANDOM_ACCESS, IntPtr.Zero);

            if (hfile == DevProp.INVALID_HANDLE_VALUE)
            {
                return(false);
            }
            DISK_GEOMETRY_EX geo = default;

            // get the disk geometry to retrieve the sector (LBA) size.
            if (!DiskGeometry(hfile, ref geo))
            {
                User32.CloseHandle(hfile);
                return(false);
            }

            // sector size (usually 512 bytes)
            uint bps = geo.Geometry.BytesPerSector;
            uint br  = 0U;
            long lp  = 0L;
            long lp2 = 0L;
            var  mm  = new MemPtr(bps * 2L);

            IO.SetFilePointerEx(hfile, 0L, ref lp, IO.FilePointerMoveMethod.Begin);
            IO.ReadFile(hfile, mm.Handle, bps * 2, ref br, IntPtr.Zero);
            var mbr = new RAW_MBR();
            var gpt = new RAW_GPT_HEADER();

            RAW_GPT_PARTITION[] gpp = null;

            // read the master boot record.
            mbr = mm.ToStructAt <RAW_MBR>(446L);

            // read the GPT structure header.
            gpt = mm.ToStructAt <RAW_GPT_HEADER>(bps);

            // check the partition header CRC.
            if (gpt.IsValid)
            {
                long lr = br;

                // seek to the LBA of the partition information.
                IO.SetFilePointerEx(hfile, (uint)(bps * gpt.PartitionEntryLBA), ref lr, IO.FilePointerMoveMethod.Begin);
                br = (uint)lr;

                // calculate the size of the partition table buffer.
                lp = gpt.NumberOfPartitions * gpt.PartitionEntryLength;

                // byte align to the sector size.
                if (lp % bps != 0L)
                {
                    lp += bps - lp % bps;
                }

                // bump up the memory pointer.
                mm.ReAlloc(lp);
                mm.ZeroMemory();

                // read the partition information into the pointer.
                IO.ReadFile(hfile, mm.Handle, (uint)lp, ref br, IntPtr.Zero);

                // check the partition table CRC.
                if (mm.CalculateCrc32() == gpt.PartitionArrayCRC32)
                {
                    // disk is valid.

                    lp = (uint)Marshal.SizeOf <RAW_GPT_PARTITION>();
                    br = 0U;
                    int i;
                    int c = (int)gpt.NumberOfPartitions;

                    gpp = new RAW_GPT_PARTITION[c + 1];

                    // populate the drive information.
                    for (i = 0; i < c; i++)
                    {
                        gpp[i] = mm.ToStructAt <RAW_GPT_PARTITION>(lp2);

                        // break on empty GUID, we are past the last partition.
                        if (gpp[i].PartitionTypeGuid == Guid.Empty)
                        {
                            break;
                        }
                        lp2 += lp;
                    }

                    // trim off excess records from the array.
                    if (i < c)
                    {
                        if (i == 0)
                        {
                            gpp = Array.Empty <RAW_GPT_PARTITION>();
                        }
                        else
                        {
                            Array.Resize(ref gpp, i);
                        }
                    }
                }
            }

            // free the resources.
            mm.Free();
            User32.CloseHandle(hfile);

            // if gpp is nothing then some error occurred somewhere and we did not succeed.
            if (gpp is null)
            {
                return(false);
            }

            // create a new RAW_GPT_DISK structure.
            gptInfo            = new RAW_GPT_DISK();
            gptInfo.Header     = gpt;
            gptInfo.Partitions = gpp;

            // we have succeeded.
            return(true);
        }
        /// <summary>
        /// Refresh the contents of the directory.
        /// </summary>
        public void Refresh(StandardIcons?iconSize = default)
        {
            if (iconSize is null)
            {
                iconSize = _IconSize;
            }

            _Children.Clear();
            _Folders.Clear();

            FileObject      fobj;
            DirectoryObject dobj;
            IShellItem      shitem = null;
            IShellFolder    shfld;
            IEnumIDList     enumer;

            MemPtr mm;
            var    mm2 = new MemPtr();

            string fp;

            string pname = ParsingName;

            if (pname is object && pname.LastIndexOf(@"\") == pname.Length - 1)
            {
                pname = pname.Substring(0, pname.Length - 1);
            }

            var argriid = Guid.Parse(ShellIIDGuid.IShellItem);
            var res     = NativeShell.SHCreateItemFromParsingName(ParsingName, IntPtr.Zero, ref argriid, ref shitem);

            _IconSize = (StandardIcons)iconSize;

            int?argiIndex = null;

            _Icon      = Resources.GetFileIcon(ParsingName, FileObject.StandardToSystem(_IconSize), iIndex: ref argiIndex);
            _IconImage = Resources.GetFileIconWPF(ParsingName, FileObject.StandardToSystem(_IconSize));

            if (res == HResult.Ok)
            {
                var argbhid  = Guid.Parse(ShellBHIDGuid.ShellFolderObject);
                var argriid1 = Guid.Parse(ShellIIDGuid.IShellFolder2);

                shitem.BindToHandler(IntPtr.Zero, ref argbhid, ref argriid1, out shfld);
                _SysInterface = shfld;

                shfld.EnumObjects(IntPtr.Zero, ShellFolderEnumerationOptions.Folders | ShellFolderEnumerationOptions.IncludeHidden | ShellFolderEnumerationOptions.NonFolders | ShellFolderEnumerationOptions.InitializeOnFirstNext, out enumer);

                if (enumer != null)
                {
                    var    glist = new List <string>();
                    uint   cf;
                    var    x = IntPtr.Zero;
                    string pout;

                    // mm.AllocCoTaskMem((MAX_PATH * 2) + 8)

                    mm2.Alloc(NativeShell.MAX_PATH * 2 + 8);

                    do
                    {
                        cf = 0U;
                        mm2.ZeroMemory(0L, NativeShell.MAX_PATH * 2 + 8);
                        res = enumer.Next(1U, out x, out cf);
                        mm  = x;

                        if (cf == 0L)
                        {
                            break;
                        }

                        if (res != HResult.Ok)
                        {
                            break;
                        }

                        mm2.IntAt(0L) = 2;

                        // shfld.GetAttributesOf(1, mm, attr)
                        shfld.GetDisplayNameOf(mm, (uint)ShellItemDesignNameOptions.ParentRelativeParsing, mm2.handle);
                        MemPtr inv;

                        if (IntPtr.Size == 4)
                        {
                            inv = (IntPtr)mm2.IntAt(1L);
                        }
                        else
                        {
                            inv = (IntPtr)mm2.LongAt(1L);
                        }

                        if (inv.Handle != IntPtr.Zero)
                        {
                            if (inv.CharAt(0L) != '\0')
                            {
                                fp = (string)inv;
                                var lpInfo = new SHFILEINFO();

                                // Dim sgfin As ShellFileGetAttributesOptions = 0,
                                // sgfout As ShellFileGetAttributesOptions = 0

                                int iFlags = User32.SHGFI_PIDL | User32.SHGFI_ATTRIBUTES;
                                lpInfo.dwAttributes = 0;
                                x = User32.SHGetItemInfo(mm.Handle, 0, ref lpInfo, Marshal.SizeOf(lpInfo), iFlags);
                                if (ParsingName is object)
                                {
                                    if (pname.LastIndexOf(@"\") == pname.Length - 1)
                                    {
                                        pname = pname.Substring(0, pname.Length - 1);
                                    }
                                    pout = $@"{pname}\{fp}";
                                }
                                else
                                {
                                    pout = fp;
                                }

                                if (lpInfo.dwAttributes == 0)
                                {
                                    lpInfo.dwAttributes = (int)FileTools.GetFileAttributes(pout);
                                }

                                FileAttributes drat = (FileAttributes)(int)(lpInfo.dwAttributes);
                                if ((lpInfo.dwAttributes & (int)FileAttributes.Directory) == (int)FileAttributes.Directory && !File.Exists(pout))
                                {
                                    dobj          = new DirectoryObject(pout, _IsSpecial, false);
                                    dobj.Parent   = this;
                                    dobj.IconSize = _IconSize;
                                    _Children.Add(dobj);
                                    _Folders.Add(dobj);
                                }
                                else
                                {
                                    fobj          = new FileObject(pout, _IsSpecial, true, _IconSize);
                                    fobj.Parent   = this;
                                    fobj.IconSize = _IconSize;
                                    _Children.Add(fobj);
                                }
                            }

                            inv.CoTaskMemFree();
                        }

                        mm.CoTaskMemFree();
                    }while (res == HResult.Ok);
                    mm2.Free();
                }
            }

            OnPropertyChanged(nameof(Folders));
            OnPropertyChanged(nameof(Icon));
            OnPropertyChanged(nameof(IconImage));
            OnPropertyChanged(nameof(IconSize));
            OnPropertyChanged(nameof(ParsingName));
            OnPropertyChanged(nameof(DisplayName));
        }
Exemple #28
0
        /// <summary>
        /// Construct an icon from the raw image data.
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        private Icon _constructIcon()
        {
            Icon _constructIconRet = default;

            if (_hIcon != IntPtr.Zero)
            {
                User32.DestroyIcon(_hIcon);
                _hIcon = IntPtr.Zero;
            }

            MemPtr mm  = (MemPtr)_image;
            var    bmp = mm.ToStruct <BITMAPINFOHEADER>();

            IntPtr hBmp;
            IntPtr ptr;
            IntPtr ppBits = new IntPtr();

            var lpicon = default(ICONINFO);

            IntPtr hicon;
            IntPtr hBmpMask = new IntPtr();

            bool hasMask;

            if (bmp.biHeight == bmp.biWidth * 2)
            {
                hasMask      = true;
                bmp.biHeight = (int)(bmp.biHeight / 2d);
            }
            else
            {
                hasMask = false;
            }

            bmp.biSizeImage = (int)(bmp.biWidth * bmp.biHeight * (bmp.biBitCount / 8d));

            bmp.biXPelsPerMeter = (int)(24.5d * 1000d);
            bmp.biYPelsPerMeter = (int)(24.5d * 1000d);

            bmp.biClrUsed      = 0;
            bmp.biClrImportant = 0;
            bmp.biPlanes       = 1;

            Marshal.StructureToPtr(bmp, mm.Handle, false);

            ptr = mm.Handle + bmp.biSize;

            if (bmp.biSize != 40)
            {
                return(null);
            }

            hBmp = User32.CreateDIBSection(IntPtr.Zero, mm.Handle, 0U, ref ppBits, IntPtr.Zero, 0);

            Native.MemCpy(ptr, ppBits, bmp.biSizeImage);

            if (hasMask)
            {
                ptr             = ptr + bmp.biSizeImage;
                bmp.biBitCount  = 1;
                bmp.biSizeImage = 0;
                Marshal.StructureToPtr(bmp, mm.Handle, false);
                hBmpMask = User32.CreateDIBSection(IntPtr.Zero, mm.Handle, 0U, ref ppBits, IntPtr.Zero, 0);
                Native.MemCpy(ptr, ppBits, (long)(Math.Max(bmp.biWidth, 32) * bmp.biHeight / 8d));
            }

            lpicon.fIcon    = 1;
            lpicon.hbmColor = hBmp;
            lpicon.hbmMask  = hBmpMask;
            hicon           = User32.CreateIconIndirect(ref lpicon);
            NativeShell.DeleteObject(hBmp);
            if (hasMask)
            {
                NativeShell.DeleteObject(hBmpMask);
            }
            _constructIconRet = Icon.FromHandle(hicon);
            _hIcon            = hicon;
            mm.Free();
            return(_constructIconRet);
        }
Exemple #29
0
        private void StartWatching(HidDeviceInfo d)
        {
            IntPtr h;

            int i = 0;

            if (_devThread is object)
            {
                StopWatching();
            }

            var s = new ObservableCollection <string>();

            _lastDevice = d;

            this.ViewingArea.ItemsSource = s;

            for (i = 0; i <= 255; i++)
            {
                s.Add("");
            }

            var th = new Thread(() =>
            {
                cts = new CancellationTokenSource();
                h   = HidFeatures.OpenHid(d);
                if ((long)h <= 0L)
                {
                    return;
                }
                var mm = new MemPtr(65L);
                try
                {
                    do
                    {
                        this.Dispatcher.Invoke(() =>
                        {
                            for (i = 0; i <= 255; i++)
                            {
                                mm.LongAtAbsolute(1L) = 0L;
                                mm.ByteAt(0L)         = (byte)i;
                                if (HidD_GetFeature(h, mm, 65))
                                {
                                    s[i] = "HID CODE " + i.ToString("X2") + " = " + mm.IntAtAbsolute(1L);
                                }
                            }
                        });

                        Thread.Sleep(1000);
                        if (cts is null || cts.IsCancellationRequested)
                        {
                            break;
                        }
                    }while (true);
                    mm.Free();
                    HidFeatures.CloseHid(h);
                    cts = null;
                    return;
                }
                catch (ThreadAbortException)
                {
                    mm.Free();
                    HidFeatures.CloseHid(h);
                    cts = null;
                    return;
                }
                catch (Exception)
                {
                    mm.Free();
                    HidFeatures.CloseHid(h);
                    cts = null;
                    return;
                }
            });

            th.IsBackground = true;
            th.SetApartmentState(ApartmentState.STA);
            _devThread = th;
            th.Start();
        }
        /// <summary>
        /// Gets a collection of fonts based on the specified criteria.
        /// </summary>
        /// <param name="families">Bit Field representing which font families to retrieve.</param>
        /// <param name="pitch">Specify the desired pitch.</param>
        /// <param name="charset">Specify the desired character set.</param>
        /// <param name="weight">Specify the desired weight.</param>
        /// <param name="Script">Specify the desired script(s) (this can be a String or an array of Strings).</param>
        /// <param name="Style">Specify the desired style(s) (this can be a String or an array of Strings).</param>
        /// <returns></returns>
        public static FontCollection GetFonts(FontFamilies families = FontFamilies.DontCare, FontPitch pitch = FontPitch.Default, FontCharSet charset = FontCharSet.Default, FontWeight weight = FontWeight.DontCare, object Script = null, object Style = null)
        {
            IntPtr hdc;

            var fonts = new List <ENUMLOGFONTEX>();

            var lf = new LOGFONT();

            string s;

            MemPtr mm = new MemPtr();

            string[] wscript;
            string[] wstyle;

            if (Script is null)
            {
                wscript = new[] { "Western" };
            }
            else if (Script is string)
            {
                wscript = new[] { (string)(Script) };
            }
            else if (Script is string[])
            {
                wscript = (string[])Script;
            }
            else
            {
                throw new ArgumentException("Invalid parameter type for Script");
            }

            if (Style is null)
            {
                wstyle = new[] { "", "Normal", "Regular" };
            }
            else if (Style is string)
            {
                wstyle = new[] { (string)(Style) };
            }
            else if (Style is string[])
            {
                wstyle = (string[])Style;
            }
            else
            {
                throw new ArgumentException("Invalid parameter type for Style");
            }

            lf.lfCharSet  = (byte)charset;
            lf.lfFaceName = "";
            mm.Alloc(Marshal.SizeOf(lf));
            mm.FromStruct(lf);
            hdc = User32.CreateDC("DISPLAY", null, IntPtr.Zero, IntPtr.Zero);

            int  e;
            bool bo = false;

            e = EnumFontFamiliesEx(hdc, mm, (ref ENUMLOGFONTEX lpelfe, IntPtr lpntme, uint FontType, IntPtr lParam) =>
            {
                int z;
                if (fonts is null)
                {
                    z = 0;
                }
                else
                {
                    z = fonts.Count;
                }


                // make sure it's the normal, regular version

                bo = false;
                foreach (var y in wstyle)
                {
                    if ((y.ToLower() ?? "") == (lpelfe.elfStyle.ToLower() ?? ""))
                    {
                        bo = true;
                        break;
                    }
                }

                if (bo == false)
                {
                    return(1);
                }
                bo = false;
                foreach (var y in wscript)
                {
                    if ((y.ToLower() ?? "") == (lpelfe.elfScript.ToLower() ?? ""))
                    {
                        bo = true;
                        break;
                    }
                }

                if (bo == false)
                {
                    return(1);
                }
                bo = false;
                if (weight != FontWeight.DontCare && lpelfe.elfLogFont.lfWeight != (int)weight)
                {
                    return(1);
                }

                // we don't really need two of the same font.
                if (z > 0)
                {
                    if ((lpelfe.elfFullName ?? "") == (fonts[z - 1].elfFullName ?? ""))
                    {
                        return(1);
                    }
                }

                // the @ indicates a vertical writing font which we definitely do not want.
                if (lpelfe.elfFullName.Substring(0, 1) == "@")
                {
                    return(1);
                }
                if (!CheckFamily(lpelfe.elfLogFont, families))
                {
                    return(1);
                }

                // lpelfe.elfLogFont.lfCharSet = charset
                // If (lpelfe.elfLogFont.lfCharSet <> charset) Then Return 1

                if (pitch != FontPitch.Default && (lpelfe.elfLogFont.lfPitchAndFamily & 3) != (int)pitch)
                {
                    return(1);
                }
                fonts.Add(lpelfe);
                return(1);
            }, IntPtr.Zero, 0U);
            User32.DeleteDC(hdc);
            mm.Free();
            if (e == 0)
            {
                e = User32.GetLastError();
                s = NativeError.Message;
            }

            FontInfo nf;
            var      ccol = new FontCollection();

            foreach (var f in fonts)
            {
                nf = new FontInfo(f);
                ccol.Add(nf);
            }

            ccol.Sort();
            return(ccol);
        }