/// <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); }
/// <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); }
/// <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); }
/// <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); }
/// <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); }
/// <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); }
static SysInfo() { // let's get some version information! var mm = new MemPtr(); GetNativeSystemInfo(ref nativeEnv); _memInfo.dwLength = Marshal.SizeOf(_memInfo); GlobalMemoryStatusEx(ref _memInfo); // now let's figure out how many processors we have on this system MemPtr org; var lp = new SystemLogicalProcessorInformation(); SystemLogicalProcessorInformation[] rets; int i; int c; // The maximum number of processors for any version of Windows is 128, we'll allocate more for extra information. mm.Alloc(Marshal.SizeOf(lp) * 1024); // record the original memory pointer org = mm; var lRet = (int)mm.Length; GetLogicalProcessorInformation(mm, ref lRet); c = (int)(lRet / (double)Marshal.SizeOf(lp)); rets = new SystemLogicalProcessorInformation[c]; nativeEnv.nop = 0; for (i = 0; i < c; i++) { rets[i] = mm.ToStruct <SystemLogicalProcessorInformation>(); mm += Marshal.SizeOf(lp); // what we're really after are the number of cores. if (rets[i].Relationship == LogicalProcessorRelationship.RelationProcessorCore) { nativeEnv.nop++; } } // store that data in case we need it for later. _procRaw = rets; // free our unmanaged resources. org.Free(); }
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); }
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); }
static SysInfo() { // ' let's get some version information! _memInfo.dwLength = Marshal.SizeOf(_memInfo); GetNativeSystemInfo(ref _sysInfo); GlobalMemoryStatusEx(ref _memInfo); // ' now let's figure out how many processors we have on this system var mm = new MemPtr(); MemPtr org; var lp = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION(); int lRet = 0; SYSTEM_LOGICAL_PROCESSOR_INFORMATION[] rets; int i; int c; // ' The maximum number of processors for any version of Windows is 128, we'll allocate more for extra information. mm.Alloc(Marshal.SizeOf(lp) * 1024); // ' record the original memory pointer org = mm; lRet = (int)mm.Length(); GetLogicalProcessorInformation(mm, ref lRet); c = (int)(lRet / (double)Marshal.SizeOf(lp)); rets = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[c]; var loopTo = c - 1; for (i = 0; i <= loopTo; i++) { rets[i] = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION)Marshal.PtrToStructure(mm.Handle, typeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION)); mm += Marshal.SizeOf(lp); // ' what we're really after are the number of cores. if (rets[i].Relationship == LOGICAL_PROCESSOR_RELATIONSHIP.RelationProcessorCore) { _sysInfo.dwNumberOfProcessors += 1; } } // ' store that data in case we need it for later. _procRaw = rets; // ' free our unmanaged resources. org.Free(); }
/// <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); }
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); }
/// <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)); }
/// <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); }
/// <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); }