i am working on listing installed drivers in system as in Device manager.
I got that list from Win32_PnPSignedDriver but it does not provide icons. Is there any way to find that or i have to add custom icons for the list. I want to generate output Like same as in Device manager.I found some reference in C/C++ but not in c#.
Here are two utility classes DeviceClass and Device that demonstrate how to do it. They don't use WMI, but the setupapi with p/invoke (and the System.Drawing's Icon class). I think this API is the only supported way to get the icon. You could then use WMI (using ids, and class ids to get more information this time using WMI).
Here is a comparison using these classes, in a Windows Form, and the Device Manager, as you see it's pretty close, but the class icon is not exactly the same, I don't know why, I've not investigated.
Last note: as expected, some devices have an icon that is different from their class and different from other icons in the same class. We can observe that in the first Audio class, the two devices don't have the same icon.
Here is the code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// This is a standard Form. I have added a TreeView control and an ImageList to the Form.
// The image list is bound to the treeview, with ColorDepth set to Depth32Bit
var classes = DeviceClass.Load(DeviceFiter.AllClasses | DeviceFiter.Present);
foreach (var cls in classes)
{
var classNode = treeView1.Nodes.Add(cls.Description);
imageList1.Images.Add(cls.Icon);
classNode.ImageIndex = imageList1.Images.Count - 1;
classNode.SelectedImageIndex = classNode.ImageIndex;
foreach (var device in cls.Devices)
{
var deviceNode = classNode.Nodes.Add(device.Name);
imageList1.Images.Add(device.Icon);
deviceNode.ImageIndex = imageList1.Images.Count - 1;
deviceNode.SelectedImageIndex = deviceNode.ImageIndex;
}
classNode.Expand();
}
// dispose (icons)
foreach (var cls in classes)
{
foreach (var device in cls.Devices)
{
device.Dispose();
}
cls.Dispose();
}
}
}
public class DeviceClass : IDisposable, IComparable, IComparable<DeviceClass>
{
private List<Device> _devices = new List<Device>();
private Icon _icon;
internal DeviceClass(Guid classId, string description)
{
ClassId = classId;
Description = description;
}
public Guid ClassId { get; }
public string Description { get; }
public Icon Icon => _icon;
public IReadOnlyList<Device> Devices => _devices;
public static IReadOnlyList<DeviceClass> Load(DeviceFiter fiter)
{
var list = new List<DeviceClass>();
var hdevinfo = SetupDiGetClassDevs(IntPtr.Zero, null, IntPtr.Zero, fiter);
try
{
var data = new SP_DEVINFO_DATA();
data.cbSize = Marshal.SizeOf<SP_DEVINFO_DATA>();
int index = 0;
while (SetupDiEnumDeviceInfo(hdevinfo, index, ref data))
{
index++;
var classId = GetGuidProperty(hdevinfo, ref data, DEVPKEY_Device_ClassGuid);
if (classId == Guid.Empty)
continue;
string classDescription = GetClassDescription(classId);
var cls = list.FirstOrDefault(c => c.ClassId == classId);
if (cls == null)
{
cls = new DeviceClass(classId, classDescription);
list.Add(cls);
SetupDiLoadClassIcon(ref classId, out IntPtr clsIcon, out int mini);
if (clsIcon != IntPtr.Zero)
{
cls._icon = Icon.FromHandle(clsIcon);
}
}
string name = GetStringProperty(hdevinfo, ref data, DEVPKEY_Device_FriendlyName);
if (string.IsNullOrWhiteSpace(name))
{
name = GetStringProperty(hdevinfo, ref data, DEVPKEY_Device_DeviceDesc);
}
Icon icon = null;
SetupDiLoadDeviceIcon(hdevinfo, ref data, 16, 16, 0, out IntPtr devIcon);
if (devIcon != IntPtr.Zero)
{
icon = Icon.FromHandle(devIcon);
}
var dev = new Device(cls, name, icon);
cls._devices.Add(dev);
}
}
finally
{
if (hdevinfo != IntPtr.Zero)
{
SetupDiDestroyDeviceInfoList(hdevinfo);
}
}
foreach (var cls in list)
{
cls._devices.Sort();
}
list.Sort();
return list;
}
int IComparable.CompareTo(object obj) => CompareTo(obj as DeviceClass);
public int CompareTo(DeviceClass other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
return Description.CompareTo(other.Description);
}
public void Dispose()
{
if (_icon != null)
{
_icon.Dispose();
_icon = null;
}
}
private static string GetClassDescription(Guid classId)
{
SetupDiGetClassDescription(ref classId, IntPtr.Zero, 0, out int size);
if (size == 0)
return null;
var ptr = Marshal.AllocCoTaskMem(size * 2);
try
{
if (!SetupDiGetClassDescription(ref classId, ptr, size, out size))
throw new Win32Exception(Marshal.GetLastWin32Error());
return Marshal.PtrToStringUni(ptr, size - 1);
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
private static string GetStringProperty(IntPtr hdevinfo, ref SP_DEVINFO_DATA data, DEVPROPKEY pk)
{
SetupDiGetDeviceProperty(hdevinfo, ref data, ref pk, out int propertyType, IntPtr.Zero, 0, out int size, 0);
if (size == 0)
return null;
var ptr = Marshal.AllocCoTaskMem(size);
try
{
if (!SetupDiGetDeviceProperty(hdevinfo, ref data, ref pk, out propertyType, ptr, size, out size, 0))
throw new Win32Exception(Marshal.GetLastWin32Error());
return Marshal.PtrToStringUni(ptr, (size / 2) - 1);
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
private static Guid GetGuidProperty(IntPtr hdevinfo, ref SP_DEVINFO_DATA data, DEVPROPKEY pk)
{
SetupDiGetDeviceProperty(hdevinfo, ref data, ref pk, out int propertyType, out Guid guid, 16, out int size, 0);
return guid;
}
[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public int DevInst;
public IntPtr Reserved;
}
[StructLayout(LayoutKind.Sequential)]
private struct DEVPROPKEY
{
public Guid fmtid;
public int pid;
}
private const int ERROR_NOT_FOUND = 118;
private const int ERROR_INSUFFICIENT_BUFFER = 122;
private static readonly DEVPROPKEY DEVPKEY_Device_DeviceDesc = new DEVPROPKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 2 };
private static readonly DEVPROPKEY DEVPKEY_Device_FriendlyName = new DEVPROPKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 14 };
private static readonly DEVPROPKEY DEVPKEY_Device_Class = new DEVPROPKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 9 };
private static readonly DEVPROPKEY DEVPKEY_Device_ClassGuid = new DEVPROPKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 10 };
[DllImport("setupapi", CharSet = CharSet.Unicode)]
private static extern IntPtr SetupDiGetClassDevs(IntPtr ClassGuid, [MarshalAs(UnmanagedType.LPWStr)] string Enumerator, IntPtr hwndParent, DeviceFiter Flags);
[DllImport("setupapi", SetLastError = true)]
private static extern bool SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, int MemberIndex, ref SP_DEVINFO_DATA DeviceInfoData);
[DllImport("setupapi", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiGetClassDescription(ref Guid ClassGuid, IntPtr ClassDescription, int ClassDescriptionSize, out int RequiredSize);
[DllImport("setupapi", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiLoadClassIcon(ref Guid ClassGuid, out IntPtr LargeIcon, out int MiniIconIndex);
[DllImport("setupapi", SetLastError = true)]
private static extern bool SetupDiLoadDeviceIcon(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData,
int cxIcon, int cyIcon, int Flags, out IntPtr hIcon);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiGetDeviceProperty(IntPtr DeviceInfoSet,
ref SP_DEVINFO_DATA DeviceInfoData,
ref DEVPROPKEY PropertyKey,
out int PropertyType,
IntPtr PropertyBuffer,
int PropertyBufferSize,
out int RequiredSize,
int Flags);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiGetDeviceProperty(IntPtr DeviceInfoSet,
ref SP_DEVINFO_DATA DeviceInfoData,
ref DEVPROPKEY PropertyKey,
out int PropertyType,
out Guid PropertyBuffer,
int PropertyBufferSize,
out int RequiredSize,
int Flags);
}
[Flags]
public enum DeviceFiter // DIGCF_* flags
{
Default = 1,
Present = 2,
AllClasses = 4,
Profile = 8,
DeviceInterface = 16
}
public class Device : IDisposable, IComparable, IComparable<Device>
{
internal Device(DeviceClass cls, string name, Icon icon)
{
Class = cls;
Name = name;
Icon = icon;
}
public string Name { get; }
public DeviceClass Class { get; }
public Icon Icon { get; private set; }
public override string ToString() => Name;
public void Dispose()
{
if (Icon != null)
{
Icon.Dispose();
Icon = null;
}
}
int IComparable.CompareTo(object obj) => CompareTo(obj as Device);
public int CompareTo(Device other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
return Name.CompareTo(other.Name);
}
}
There is a nice article using SHGetFileInfo function to get associated icons, i'd recommend looking into that.
You cannot do it using pure .Net or C# you will need this dll in the article.
EDIT
Maybe this MDSN Device Information will be of help
I think many of us having some errors with #Simon's codes.
Here are his revised codes:
public class DeviceClass : IDisposable, IComparable, IComparable<DeviceClass>
{
private List<Device> _devices = new List<Device>();
private Icon _icon;
internal DeviceClass(Guid classId, string description)
{
ClassId = classId;
Description = description;
}
public Guid ClassId { get; }
public string Description { get; }
public Icon Icon => _icon;
public IReadOnlyList<Device> Devices => _devices;
public static IReadOnlyList<DeviceClass> Load(DeviceFiter fiter)
{
var list = new List<DeviceClass>();
var hdevinfo = SetupDiGetClassDevs(IntPtr.Zero, null, IntPtr.Zero, fiter);
try
{
var data = new SP_DEVINFO_DATA();
data.cbSize = System.Runtime.InteropServices.Marshal.SizeOf<SP_DEVINFO_DATA>();
int index = 0;
while (SetupDiEnumDeviceInfo(hdevinfo, index, ref data))
{
index++;
var classId = GetGuidProperty(hdevinfo, ref data, DEVPKEY_Device_ClassGuid);
if (classId == Guid.Empty)
continue;
string classDescription = GetClassDescription(classId);
var cls = list.FirstOrDefault(c => c.ClassId == classId);
if (cls == null)
{
cls = new DeviceClass(classId, classDescription);
list.Add(cls);
IntPtr clsIcon;
int mini;
SetupDiLoadClassIcon(ref classId, out clsIcon, out mini);
if (clsIcon != IntPtr.Zero)
{
cls._icon = Icon.FromHandle(clsIcon);
}
}
string name = GetStringProperty(hdevinfo, ref data, DEVPKEY_Device_FriendlyName);
if (string.IsNullOrWhiteSpace(name))
{
name = GetStringProperty(hdevinfo, ref data, DEVPKEY_Device_DeviceDesc);
}
Icon icon = null;
IntPtr devIcon;
SetupDiLoadDeviceIcon(hdevinfo, ref data, 16, 16, 0, out devIcon);
if (devIcon != IntPtr.Zero)
{
icon = Icon.FromHandle(devIcon);
}
var dev = new Device(cls, name, icon);
cls._devices.Add(dev);
}
}
finally
{
if (hdevinfo != IntPtr.Zero)
{
SetupDiDestroyDeviceInfoList(hdevinfo);
}
}
foreach (var cls in list)
{
cls._devices.Sort();
}
list.Sort();
return list;
}
int IComparable.CompareTo(object obj) => CompareTo(obj as DeviceClass);
public int CompareTo(DeviceClass other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
return Description.CompareTo(other.Description);
}
public void Dispose()
{
if (_icon != null)
{
_icon.Dispose();
_icon = null;
}
}
private static string GetClassDescription(Guid classId)
{
int size = 0;
SetupDiGetClassDescription(ref classId, IntPtr.Zero, 0, out size);
if (size == 0)
return null;
var ptr = Marshal.AllocCoTaskMem(size * 2);
try
{
if (!SetupDiGetClassDescription(ref classId, ptr, size, out size))
throw new Win32Exception(Marshal.GetLastWin32Error());
return Marshal.PtrToStringUni(ptr, size - 1);
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
private static string GetStringProperty(IntPtr hdevinfo, ref SP_DEVINFO_DATA data, DEVPROPKEY pk)
{
int propertyType;
int size;
SetupDiGetDeviceProperty(hdevinfo, ref data, ref pk, out propertyType, IntPtr.Zero, 0, out size, 0);
if (size == 0)
return null;
var ptr = Marshal.AllocCoTaskMem(size);
try
{
if (!SetupDiGetDeviceProperty(hdevinfo, ref data, ref pk, out propertyType, ptr, size, out size, 0))
throw new Win32Exception(Marshal.GetLastWin32Error());
return Marshal.PtrToStringUni(ptr, (size / 2) - 1);
}
finally
{
Marshal.FreeCoTaskMem(ptr);
}
}
private static Guid GetGuidProperty(IntPtr hdevinfo, ref SP_DEVINFO_DATA data, DEVPROPKEY pk)
{
int propertyType, size;
Guid guid;
SetupDiGetDeviceProperty(hdevinfo, ref data, ref pk, out propertyType, out guid, 16, out size, 0);
return guid;
}
[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public int DevInst;
public IntPtr Reserved;
}
[StructLayout(LayoutKind.Sequential)]
private struct DEVPROPKEY
{
public Guid fmtid;
public int pid;
}
private const int ERROR_NOT_FOUND = 118;
private const int ERROR_INSUFFICIENT_BUFFER = 122;
private static readonly DEVPROPKEY DEVPKEY_Device_DeviceDesc = new DEVPROPKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 2 };
private static readonly DEVPROPKEY DEVPKEY_Device_FriendlyName = new DEVPROPKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 14 };
private static readonly DEVPROPKEY DEVPKEY_Device_Class = new DEVPROPKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 9 };
private static readonly DEVPROPKEY DEVPKEY_Device_ClassGuid = new DEVPROPKEY { fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), pid = 10 };
[DllImport("setupapi", CharSet = CharSet.Unicode)]
private static extern IntPtr SetupDiGetClassDevs(IntPtr ClassGuid, [MarshalAs(UnmanagedType.LPWStr)] string Enumerator, IntPtr hwndParent, DeviceFiter Flags);
[DllImport("setupapi", SetLastError = true)]
private static extern bool SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("setupapi", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet, int MemberIndex, ref SP_DEVINFO_DATA DeviceInfoData);
[DllImport("setupapi", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiGetClassDescription(ref Guid ClassGuid, IntPtr ClassDescription, int ClassDescriptionSize, out int RequiredSize);
[DllImport("setupapi", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiLoadClassIcon(ref Guid ClassGuid, out IntPtr LargeIcon, out int MiniIconIndex);
[DllImport("setupapi", SetLastError = true)]
private static extern bool SetupDiLoadDeviceIcon(IntPtr DeviceInfoSet, ref SP_DEVINFO_DATA DeviceInfoData,
int cxIcon, int cyIcon, int Flags, out IntPtr hIcon);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiGetDeviceProperty(IntPtr DeviceInfoSet,
ref SP_DEVINFO_DATA DeviceInfoData,
ref DEVPROPKEY PropertyKey,
out int PropertyType,
IntPtr PropertyBuffer,
int PropertyBufferSize,
out int RequiredSize,
int Flags);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool SetupDiGetDeviceProperty(IntPtr DeviceInfoSet,
ref SP_DEVINFO_DATA DeviceInfoData,
ref DEVPROPKEY PropertyKey,
out int PropertyType,
out Guid PropertyBuffer,
int PropertyBufferSize,
out int RequiredSize,
int Flags);
}
[Flags]
public enum DeviceFiter // DIGCF_* flags
{
Default = 1,
Present = 2,
AllClasses = 4,
Profile = 8,
DeviceInterface = 16
}
public class Device : IDisposable, IComparable, IComparable<Device>
{
internal Device(DeviceClass cls, string name, Icon icon)
{
Class = cls;
Name = name;
Icon = icon;
}
public string Name { get; }
public DeviceClass Class { get; }
public Icon Icon { get; private set; }
public override string ToString() => Name;
public void Dispose()
{
if (Icon != null)
{
Icon.Dispose();
Icon = null;
}
}
int IComparable.CompareTo(object obj) => CompareTo(obj as Device);
public int CompareTo(Device other)
{
if (other == null)
throw new ArgumentNullException(nameof(other));
return Name.CompareTo(other.Name);
}
}
Related
My environment is Windows 10 20H2(64bit) and Visual Studio 2019.
I am developing an app as C# WPF(.NET 5) project. And I want to write a code that HDR(High Dynamic Range) is active currently on the system.
In this document, I got some hints about Windows HDR. But I could only find articles about for UWP and DirectX.
I would ideally like to use the .NET API or Win32 API. Does Windows 10 provide those APIs?
You can use the Connecting and Configuring Displays (CCD) API.
specifically the DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO request (which is not really documented in MSDN but is defined in wingdi.h)
Here is some C# Console Application sample code that dumps for each monitor if it supports HDR and if it's enabled.
static void Main()
{
var err = GetDisplayConfigBufferSizes(QDC.QDC_ONLY_ACTIVE_PATHS, out var pathCount, out var modeCount);
if (err != 0)
throw new Win32Exception(err);
var paths = new DISPLAYCONFIG_PATH_INFO[pathCount];
var modes = new DISPLAYCONFIG_MODE_INFO[modeCount];
err = QueryDisplayConfig(QDC.QDC_ONLY_ACTIVE_PATHS, ref pathCount, paths, ref modeCount, modes, IntPtr.Zero);
if (err != 0)
throw new Win32Exception(err);
foreach (var path in paths)
{
// get display name
var info = new DISPLAYCONFIG_TARGET_DEVICE_NAME();
info.header.type = DISPLAYCONFIG_DEVICE_INFO_TYPE.DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME;
info.header.size = Marshal.SizeOf<DISPLAYCONFIG_TARGET_DEVICE_NAME>();
info.header.adapterId = path.targetInfo.adapterId;
info.header.id = path.targetInfo.id;
err = DisplayConfigGetDeviceInfo(ref info);
if (err != 0)
throw new Win32Exception(err);
var colorInfo = new DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO();
colorInfo.header.type = DISPLAYCONFIG_DEVICE_INFO_TYPE.DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO;
colorInfo.header.size = Marshal.SizeOf<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO>();
colorInfo.header.adapterId = path.targetInfo.adapterId;
colorInfo.header.id = path.targetInfo.id;
err = DisplayConfigGetDeviceInfo(ref colorInfo);
if (err != 0)
throw new Win32Exception(err);
Console.WriteLine(info.monitorFriendlyDeviceName);
Console.WriteLine(" Advanced Color Supported: " + colorInfo.advancedColorSupported);
Console.WriteLine(" Advanced Color Enabled : " + colorInfo.advancedColorEnabled);
Console.WriteLine();
}
}
private enum DISPLAYCONFIG_DEVICE_INFO_TYPE
{
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME = 1,
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME = 2,
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_PREFERRED_MODE = 3,
DISPLAYCONFIG_DEVICE_INFO_GET_ADAPTER_NAME = 4,
DISPLAYCONFIG_DEVICE_INFO_SET_TARGET_PERSISTENCE = 5,
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_BASE_TYPE = 6,
DISPLAYCONFIG_DEVICE_INFO_GET_SUPPORT_VIRTUAL_RESOLUTION = 7,
DISPLAYCONFIG_DEVICE_INFO_SET_SUPPORT_VIRTUAL_RESOLUTION = 8,
DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO = 9,
DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE = 10,
DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL = 11,
}
private enum DISPLAYCONFIG_COLOR_ENCODING
{
DISPLAYCONFIG_COLOR_ENCODING_RGB = 0,
DISPLAYCONFIG_COLOR_ENCODING_YCBCR444 = 1,
DISPLAYCONFIG_COLOR_ENCODING_YCBCR422 = 2,
DISPLAYCONFIG_COLOR_ENCODING_YCBCR420 = 3,
DISPLAYCONFIG_COLOR_ENCODING_INTENSITY = 4,
}
private enum DISPLAYCONFIG_SCALING
{
DISPLAYCONFIG_SCALING_IDENTITY = 1,
DISPLAYCONFIG_SCALING_CENTERED = 2,
DISPLAYCONFIG_SCALING_STRETCHED = 3,
DISPLAYCONFIG_SCALING_ASPECTRATIOCENTEREDMAX = 4,
DISPLAYCONFIG_SCALING_CUSTOM = 5,
DISPLAYCONFIG_SCALING_PREFERRED = 128,
}
private enum DISPLAYCONFIG_ROTATION
{
DISPLAYCONFIG_ROTATION_IDENTITY = 1,
DISPLAYCONFIG_ROTATION_ROTATE90 = 2,
DISPLAYCONFIG_ROTATION_ROTATE180 = 3,
}
private enum DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY
{
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER = -1,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HD15 = 0,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SVIDEO = 1,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_COMPOSITE_VIDEO = 2,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_COMPONENT_VIDEO = 3,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI = 4,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI = 5,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_LVDS = 6,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_D_JPN = 8,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SDI = 9,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EXTERNAL = 10,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EMBEDDED = 11,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EXTERNAL = 12,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EMBEDDED = 13,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SDTVDONGLE = 14,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_MIRACAST = 15,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INDIRECT_WIRED = 16,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INDIRECT_VIRTUAL = 17,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL = unchecked((int)0x80000000),
}
private enum DISPLAYCONFIG_TOPOLOGY_ID
{
DISPLAYCONFIG_TOPOLOGY_INTERNAL = 0x00000001,
DISPLAYCONFIG_TOPOLOGY_CLONE = 0x00000002,
DISPLAYCONFIG_TOPOLOGY_EXTEND = 0x00000004,
DISPLAYCONFIG_TOPOLOGY_EXTERNAL = 0x00000008,
}
private enum DISPLAYCONFIG_PATH
{
DISPLAYCONFIG_PATH_ACTIVE = 0x00000001,
DISPLAYCONFIG_PATH_PREFERRED_UNSCALED = 0x00000004,
DISPLAYCONFIG_PATH_SUPPORT_VIRTUAL_MODE = 0x00000008,
}
private enum DISPLAYCONFIG_SOURCE_FLAGS
{
DISPLAYCONFIG_SOURCE_IN_USE = 0x00000001,
}
private enum DISPLAYCONFIG_TARGET_FLAGS
{
DISPLAYCONFIG_TARGET_IN_USE = 0x00000001,
DISPLAYCONFIG_TARGET_FORCIBLE = 0x00000002,
DISPLAYCONFIG_TARGET_FORCED_AVAILABILITY_BOOT = 0x00000004,
DISPLAYCONFIG_TARGET_FORCED_AVAILABILITY_PATH = 0x00000008,
DISPLAYCONFIG_TARGET_FORCED_AVAILABILITY_SYSTEM = 0x00000010,
DISPLAYCONFIG_TARGET_IS_HMD = 0x00000020,
}
private enum QDC
{
QDC_ALL_PATHS = 0x00000001,
QDC_ONLY_ACTIVE_PATHS = 0x00000002,
QDC_DATABASE_CURRENT = 0x00000004,
QDC_VIRTUAL_MODE_AWARE = 0x00000010,
QDC_INCLUDE_HMD = 0x00000020,
}
private enum DISPLAYCONFIG_SCANLINE_ORDERING
{
DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED = 0,
DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE = 1,
DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED = 2,
DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST = DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED,
DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST = 3,
}
private enum DISPLAYCONFIG_PIXELFORMAT
{
DISPLAYCONFIG_PIXELFORMAT_8BPP = 1,
DISPLAYCONFIG_PIXELFORMAT_16BPP = 2,
DISPLAYCONFIG_PIXELFORMAT_24BPP = 3,
DISPLAYCONFIG_PIXELFORMAT_32BPP = 4,
DISPLAYCONFIG_PIXELFORMAT_NONGDI = 5,
}
private enum DISPLAYCONFIG_MODE_INFO_TYPE
{
DISPLAYCONFIG_MODE_INFO_TYPE_SOURCE = 1,
DISPLAYCONFIG_MODE_INFO_TYPE_TARGET = 2,
DISPLAYCONFIG_MODE_INFO_TYPE_DESKTOP_IMAGE = 3,
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_DEVICE_INFO_HEADER
{
public DISPLAYCONFIG_DEVICE_INFO_TYPE type;
public int size;
public LUID adapterId;
public uint id;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO
{
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
public uint value;
public DISPLAYCONFIG_COLOR_ENCODING colorEncoding;
public int bitsPerColorChannel;
public bool advancedColorSupported => (value & 0x1) == 0x1;
public bool advancedColorEnabled => (value & 0x2) == 0x2;
public bool wideColorEnforced => (value & 0x4) == 0x4;
public bool advancedColorForceDisabled => (value & 0x8) == 0x8;
}
[StructLayout(LayoutKind.Sequential)]
private struct POINTL
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private struct LUID
{
public uint LowPart;
public int HighPart;
public long Value => ((long)HighPart << 32) | LowPart;
public override string ToString() => Value.ToString();
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_SOURCE_MODE
{
public uint width;
public uint height;
public DISPLAYCONFIG_PIXELFORMAT pixelFormat;
public POINTL position;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_RATIONAL
{
public uint Numerator;
public uint Denominator;
public override string ToString() => Numerator + " / " + Denominator;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_2DREGION
{
public uint cx;
public uint cy;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_DESKTOP_IMAGE_INFO
{
public POINTL PathSourceSize;
public RECT DesktopImageRegion;
public RECT DesktopImageClip;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_VIDEO_SIGNAL_INFO
{
public ulong pixelRate;
public DISPLAYCONFIG_RATIONAL hSyncFreq;
public DISPLAYCONFIG_RATIONAL vSyncFreq;
public DISPLAYCONFIG_2DREGION activeSize;
public DISPLAYCONFIG_2DREGION totalSize;
public uint videoStandard;
public DISPLAYCONFIG_SCANLINE_ORDERING scanLineOrdering;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_TARGET_MODE
{
public DISPLAYCONFIG_VIDEO_SIGNAL_INFO targetVideoSignalInfo;
}
[StructLayout(LayoutKind.Explicit)]
private struct DISPLAYCONFIG_MODE_INFO_union
{
[FieldOffset(0)]
public DISPLAYCONFIG_TARGET_MODE targetMode;
[FieldOffset(0)]
public DISPLAYCONFIG_SOURCE_MODE sourceMode;
[FieldOffset(0)]
public DISPLAYCONFIG_DESKTOP_IMAGE_INFO desktopImageInfo;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_PATH_SOURCE_INFO
{
public LUID adapterId;
public uint id;
public uint modeInfoIdx;
public DISPLAYCONFIG_SOURCE_FLAGS statusFlags;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_PATH_TARGET_INFO
{
public LUID adapterId;
public uint id;
public uint modeInfoIdx;
public DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY outputTechnology;
public DISPLAYCONFIG_ROTATION rotation;
public DISPLAYCONFIG_SCALING scaling;
public DISPLAYCONFIG_RATIONAL refreshRate;
public DISPLAYCONFIG_SCANLINE_ORDERING scanLineOrdering;
public bool targetAvailable;
public DISPLAYCONFIG_TARGET_FLAGS statusFlags;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_PATH_INFO
{
public DISPLAYCONFIG_PATH_SOURCE_INFO sourceInfo;
public DISPLAYCONFIG_PATH_TARGET_INFO targetInfo;
public DISPLAYCONFIG_PATH flags;
}
[StructLayout(LayoutKind.Sequential)]
private struct DISPLAYCONFIG_MODE_INFO
{
public DISPLAYCONFIG_MODE_INFO_TYPE infoType;
public uint id;
public LUID adapterId;
public DISPLAYCONFIG_MODE_INFO_union info;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DISPLAYCONFIG_SOURCE_DEVICE_NAME
{
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string viewGdiDeviceName;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS
{
public uint value;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct DISPLAYCONFIG_TARGET_DEVICE_NAME
{
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
public DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS flags;
public DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY outputTechnology;
public ushort edidManufactureId;
public ushort edidProductCodeId;
public uint connectorInstance;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string monitorFriendlyDeviceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string monitorDevicePat;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32")]
private static extern int GetDisplayConfigBufferSizes(QDC flags, out int numPathArrayElements, out int numModeInfoArrayElements);
[DllImport("user32")]
private static extern int QueryDisplayConfig(QDC flags, ref int numPathArrayElements, [In, Out] DISPLAYCONFIG_PATH_INFO[] pathArray, ref int numModeInfoArrayElements, [In, Out] DISPLAYCONFIG_MODE_INFO[] modeInfoArray, out DISPLAYCONFIG_TOPOLOGY_ID currentTopologyId);
[DllImport("user32")]
private static extern int QueryDisplayConfig(QDC flags, ref int numPathArrayElements, [In, Out] DISPLAYCONFIG_PATH_INFO[] pathArray, ref int numModeInfoArrayElements, [In, Out] DISPLAYCONFIG_MODE_INFO[] modeInfoArray, IntPtr currentTopologyId);
[DllImport("user32")]
private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO requestPacket);
[DllImport("user32")]
private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_SOURCE_DEVICE_NAME requestPacket);
[DllImport("user32")]
private static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_TARGET_DEVICE_NAME requestPacket);
I trying to fill Wacom tablet screen with my application. How can I find this screen working area?
At this moment I just trying to find this screen by Device Friendly name using ScreenInterrogatory class (code below), but it requires me to know device name. I looking for a way to do this for any Wacom device without knowing the device name (using Wintab api).
//
public Screen GetWacomWorkingArea(string wacomDeviceName)
{
foreach(var screen in System.Windows.Forms.Screen.AllScreens)
{
if(screen.DeviceFriendlyName == wacomDeviceName)
{
return screen.WorkingArea;
}
}
}
//
public static class ScreenInterrogatory
{
public const int ERROR_SUCCESS = 0;
#region enums
public enum QUERY_DEVICE_CONFIG_FLAGS : uint
{
QDC_ALL_PATHS = 0x00000001,
QDC_ONLY_ACTIVE_PATHS = 0x00000002,
QDC_DATABASE_CURRENT = 0x00000004
}
public enum DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY : uint
{
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER = 0xFFFFFFFF,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HD15 = 0,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SVIDEO = 1,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_COMPOSITE_VIDEO = 2,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_COMPONENT_VIDEO = 3,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DVI = 4,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_HDMI = 5,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_LVDS = 6,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_D_JPN = 8,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SDI = 9,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EXTERNAL = 10,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_DISPLAYPORT_EMBEDDED = 11,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EXTERNAL = 12,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_UDI_EMBEDDED = 13,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_SDTVDONGLE = 14,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_MIRACAST = 15,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL = 0x80000000,
DISPLAYCONFIG_OUTPUT_TECHNOLOGY_FORCE_UINT32 = 0xFFFFFFFF
}
public enum DISPLAYCONFIG_SCANLINE_ORDERING : uint
{
DISPLAYCONFIG_SCANLINE_ORDERING_UNSPECIFIED = 0,
DISPLAYCONFIG_SCANLINE_ORDERING_PROGRESSIVE = 1,
DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED = 2,
DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_UPPERFIELDFIRST = DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED,
DISPLAYCONFIG_SCANLINE_ORDERING_INTERLACED_LOWERFIELDFIRST = 3,
DISPLAYCONFIG_SCANLINE_ORDERING_FORCE_UINT32 = 0xFFFFFFFF
}
public enum DISPLAYCONFIG_ROTATION : uint
{
DISPLAYCONFIG_ROTATION_IDENTITY = 1,
DISPLAYCONFIG_ROTATION_ROTATE90 = 2,
DISPLAYCONFIG_ROTATION_ROTATE180 = 3,
DISPLAYCONFIG_ROTATION_ROTATE270 = 4,
DISPLAYCONFIG_ROTATION_FORCE_UINT32 = 0xFFFFFFFF
}
public enum DISPLAYCONFIG_SCALING : uint
{
DISPLAYCONFIG_SCALING_IDENTITY = 1,
DISPLAYCONFIG_SCALING_CENTERED = 2,
DISPLAYCONFIG_SCALING_STRETCHED = 3,
DISPLAYCONFIG_SCALING_ASPECTRATIOCENTEREDMAX = 4,
DISPLAYCONFIG_SCALING_CUSTOM = 5,
DISPLAYCONFIG_SCALING_PREFERRED = 128,
DISPLAYCONFIG_SCALING_FORCE_UINT32 = 0xFFFFFFFF
}
public enum DISPLAYCONFIG_PIXELFORMAT : uint
{
DISPLAYCONFIG_PIXELFORMAT_8BPP = 1,
DISPLAYCONFIG_PIXELFORMAT_16BPP = 2,
DISPLAYCONFIG_PIXELFORMAT_24BPP = 3,
DISPLAYCONFIG_PIXELFORMAT_32BPP = 4,
DISPLAYCONFIG_PIXELFORMAT_NONGDI = 5,
DISPLAYCONFIG_PIXELFORMAT_FORCE_UINT32 = 0xffffffff
}
public enum DISPLAYCONFIG_MODE_INFO_TYPE : uint
{
DISPLAYCONFIG_MODE_INFO_TYPE_SOURCE = 1,
DISPLAYCONFIG_MODE_INFO_TYPE_TARGET = 2,
DISPLAYCONFIG_MODE_INFO_TYPE_FORCE_UINT32 = 0xFFFFFFFF
}
public enum DISPLAYCONFIG_DEVICE_INFO_TYPE : uint
{
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME = 1,
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME = 2,
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_PREFERRED_MODE = 3,
DISPLAYCONFIG_DEVICE_INFO_GET_ADAPTER_NAME = 4,
DISPLAYCONFIG_DEVICE_INFO_SET_TARGET_PERSISTENCE = 5,
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_BASE_TYPE = 6,
DISPLAYCONFIG_DEVICE_INFO_FORCE_UINT32 = 0xFFFFFFFF
}
#endregion
#region structs
[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public uint LowPart;
public int HighPart;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_PATH_SOURCE_INFO
{
public LUID adapterId;
public uint id;
public uint modeInfoIdx;
public uint statusFlags;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_PATH_TARGET_INFO
{
public LUID adapterId;
public uint id;
public uint modeInfoIdx;
private DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY outputTechnology;
private DISPLAYCONFIG_ROTATION rotation;
private DISPLAYCONFIG_SCALING scaling;
private DISPLAYCONFIG_RATIONAL refreshRate;
private DISPLAYCONFIG_SCANLINE_ORDERING scanLineOrdering;
public bool targetAvailable;
public uint statusFlags;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_RATIONAL
{
public uint Numerator;
public uint Denominator;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_PATH_INFO
{
public DISPLAYCONFIG_PATH_SOURCE_INFO sourceInfo;
public DISPLAYCONFIG_PATH_TARGET_INFO targetInfo;
public uint flags;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_2DREGION
{
public uint cx;
public uint cy;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_VIDEO_SIGNAL_INFO
{
public ulong pixelRate;
public DISPLAYCONFIG_RATIONAL hSyncFreq;
public DISPLAYCONFIG_RATIONAL vSyncFreq;
public DISPLAYCONFIG_2DREGION activeSize;
public DISPLAYCONFIG_2DREGION totalSize;
public uint videoStandard;
public DISPLAYCONFIG_SCANLINE_ORDERING scanLineOrdering;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_TARGET_MODE
{
public DISPLAYCONFIG_VIDEO_SIGNAL_INFO targetVideoSignalInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct POINTL
{
private int x;
private int y;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_SOURCE_MODE
{
public uint width;
public uint height;
public DISPLAYCONFIG_PIXELFORMAT pixelFormat;
public POINTL position;
}
[StructLayout(LayoutKind.Explicit)]
public struct DISPLAYCONFIG_MODE_INFO_UNION
{
[FieldOffset(0)]
public DISPLAYCONFIG_TARGET_MODE targetMode;
[FieldOffset(0)]
public DISPLAYCONFIG_SOURCE_MODE sourceMode;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_MODE_INFO
{
public DISPLAYCONFIG_MODE_INFO_TYPE infoType;
public uint id;
public LUID adapterId;
public DISPLAYCONFIG_MODE_INFO_UNION modeInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS
{
public uint value;
}
[StructLayout(LayoutKind.Sequential)]
public struct DISPLAYCONFIG_DEVICE_INFO_HEADER
{
public DISPLAYCONFIG_DEVICE_INFO_TYPE type;
public uint size;
public LUID adapterId;
public uint id;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DISPLAYCONFIG_TARGET_DEVICE_NAME
{
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
public DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS flags;
public DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY outputTechnology;
public ushort edidManufactureId;
public ushort edidProductCodeId;
public uint connectorInstance;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string monitorFriendlyDeviceName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string monitorDevicePath;
}
#endregion
#region DLL-Imports
[DllImport("user32.dll")]
public static extern int GetDisplayConfigBufferSizes(
QUERY_DEVICE_CONFIG_FLAGS flags, out uint numPathArrayElements, out uint numModeInfoArrayElements);
[DllImport("user32.dll")]
public static extern int QueryDisplayConfig(
QUERY_DEVICE_CONFIG_FLAGS flags,
ref uint numPathArrayElements, [Out] DISPLAYCONFIG_PATH_INFO[] PathInfoArray,
ref uint numModeInfoArrayElements, [Out] DISPLAYCONFIG_MODE_INFO[] ModeInfoArray,
IntPtr currentTopologyId
);
[DllImport("user32.dll")]
public static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_TARGET_DEVICE_NAME deviceName);
#endregion
private static string MonitorFriendlyName(LUID adapterId, uint targetId)
{
var deviceName = new DISPLAYCONFIG_TARGET_DEVICE_NAME
{
header =
{
size = (uint)Marshal.SizeOf(typeof (DISPLAYCONFIG_TARGET_DEVICE_NAME)),
adapterId = adapterId,
id = targetId,
type = DISPLAYCONFIG_DEVICE_INFO_TYPE.DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME
}
};
var error = DisplayConfigGetDeviceInfo(ref deviceName);
if (error != ERROR_SUCCESS)
throw new Win32Exception(error);
return deviceName.monitorFriendlyDeviceName;
}
private static IEnumerable<string> GetAllMonitorsFriendlyNames()
{
uint pathCount, modeCount;
var error = GetDisplayConfigBufferSizes(QUERY_DEVICE_CONFIG_FLAGS.QDC_ONLY_ACTIVE_PATHS, out pathCount, out modeCount);
if (error != ERROR_SUCCESS)
throw new Win32Exception(error);
var displayPaths = new DISPLAYCONFIG_PATH_INFO[pathCount];
var displayModes = new DISPLAYCONFIG_MODE_INFO[modeCount];
error = QueryDisplayConfig(QUERY_DEVICE_CONFIG_FLAGS.QDC_ONLY_ACTIVE_PATHS,
ref pathCount, displayPaths, ref modeCount, displayModes, IntPtr.Zero);
if (error != ERROR_SUCCESS)
throw new Win32Exception(error);
for (var i = 0; i < modeCount; i++)
if (displayModes[i].infoType == DISPLAYCONFIG_MODE_INFO_TYPE.DISPLAYCONFIG_MODE_INFO_TYPE_TARGET)
yield return MonitorFriendlyName(displayModes[i].adapterId, displayModes[i].id);
}
public static string DeviceFriendlyName(this Screen screen)
{
var allFriendlyNames = GetAllMonitorsFriendlyNames();
for (var index = 0; index < Screen.AllScreens.Length; index++)
if (Equals(screen, Screen.AllScreens[index]))
return allFriendlyNames.ToArray()[index];
return null;
}
}
Trying to use the following code example which works fine in WinForm application but not in VSTO. Is there some sort of permissions that allow access?
Can set the default printer but can't get or set printer settings.
Get the following exception from within addin:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
http://www.pinvoke.net/default.aspx/winspool.SetDefaultPrinter
http://www.pinvoke.net/default.aspx/winspool/OpenPrinter.html
visual studio project template is a {Word/Outlook} 2013 and 2016 VSTO Add-in
string name = #"\\{printer server name}\{printer name}";
PRNsettings p = new PRNsettings();
var v = p.ChangePrinterSetting(name, new PrinterData { colour = 1, copies = 1, duplex = 1, source = 7 });
public class PrinterData
{
public PrinterData()
{
copies = -1;
colour = -1;
duplex = -1;
source = -1;
}
public int copies { get; set; }
public int colour { get; set; }
public int duplex { get; set; }
public int source { get; set; }
}
public class PRNsettings
{
private IntPtr hPrinter = new System.IntPtr();
private PRINTER_DEFAULTS PrinterValues = new PRINTER_DEFAULTS();
private PRINTER_INFO_2 pinfo = new PRINTER_INFO_2();
private DEVMODE dm;
private IntPtr ptrDM;
private IntPtr ptrPrinterInfo;
private int sizeOfDevMode = 0;
private int lastError;
private int nBytesNeeded;
private long nRet;
private int intError;
private System.Int32 nJunk;
private IntPtr yDevModeData;
[DllImport("kernel32.dll", EntryPoint = "GetLastError", SetLastError = false, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern Int32 GetLastError();
[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesA", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter,
[MarshalAs(UnmanagedType.LPStr)] string pDeviceNameg, IntPtr pDevModeOutput, ref IntPtr pDevModeInput, int fMode);
[DllImport("winspool.Drv", EntryPoint = "GetPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern bool GetPrinter(IntPtr hPrinter, Int32 dwLevel, IntPtr pPrinter, Int32 dwBuf, out Int32 dwNeeded);
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, PRINTER_DEFAULTS pDefault);
[DllImport("winspool.drv", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern bool SetPrinter(IntPtr hPrinter, int Level, IntPtr pPrinter, int Command);
[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool SetDefaultPrinter(string Name);
[StructLayout(LayoutKind.Sequential)]
public struct PRINTER_DEFAULTS
{
public int pDatatype;
public int pDevMode;
public int DesiredAccess;
}
[StructLayout(LayoutKind.Sequential)]
private struct PRINTER_INFO_2
{
[MarshalAs(UnmanagedType.LPStr)] public string pServerName;
[MarshalAs(UnmanagedType.LPStr)] public string pPrinterName;
[MarshalAs(UnmanagedType.LPStr)] public string pShareName;
[MarshalAs(UnmanagedType.LPStr)] public string pPortName;
[MarshalAs(UnmanagedType.LPStr)] public string pDriverName;
[MarshalAs(UnmanagedType.LPStr)] public string pComment;
[MarshalAs(UnmanagedType.LPStr)] public string pLocation;
public IntPtr pDevMode;
[MarshalAs(UnmanagedType.LPStr)] public string pSepFile;
[MarshalAs(UnmanagedType.LPStr)] public string pPrintProcessor;
[MarshalAs(UnmanagedType.LPStr)] public string pDatatype;
[MarshalAs(UnmanagedType.LPStr)] public string pParameters;
public IntPtr pSecurityDescriptor;
public Int32 Attributes;
public Int32 Priority;
public Int32 DefaultPriority;
public Int32 StartTime;
public Int32 UntilTime;
public Int32 Status;
public Int32 cJobs;
public Int32 AveragePPM;
}
private const short CCDEVICENAME = 32;
private const short CCFORMNAME = 32;
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCDEVICENAME)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public short dmOrientation;
public short dmPaperSize;
public short dmPaperLength;
public short dmPaperWidth;
public short dmScale;
public short dmCopies;
public short dmDefaultSource;
public short dmPrintQuality;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCFORMNAME)]
public string dmFormName;
public short dmUnusedPadding;
public short dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public uint dmMediaType;
}
private const int DM_DUPLEX = 0x1000;
private const int DM_IN_BUFFER = 8;
private const int DM_OUT_BUFFER = 2;
private const int PRINTER_ACCESS_ADMINISTER = 0x4;
private const int PRINTER_ACCESS_USE = 0x8;
private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
private const int PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE);
public int returnSource;
public int returnDuplex;
public int returnColor;
public int returnCopies;
public bool SetDefault(string name)
{
try
{
return SetDefaultPrinter(name);
}
catch (Exception) { return false; }
}
public bool ChangePrinterSetting(string PrinterName, PrinterData PS)
{
try
{
dm = this.GetPrinterSettings(PrinterName);
// Sent back to allow reset of the settings back to original.
returnSource = dm.dmDefaultSource;
returnDuplex = dm.dmDuplex;
returnColor = dm.dmColor;
returnCopies = dm.dmCopies;
if (PS.source > -1)
dm.dmDefaultSource = (short)PS.source;
if (PS.duplex > -1)
dm.dmDuplex = (short)PS.duplex;
if (PS.colour > -1)
dm.dmColor = (short)PS.colour;
if (PS.copies > -1)
dm.dmCopies = (short)PS.copies;
Marshal.StructureToPtr(dm, yDevModeData, true);
pinfo.pDevMode = yDevModeData;
pinfo.pSecurityDescriptor = IntPtr.Zero;
Marshal.StructureToPtr(pinfo, ptrPrinterInfo, false);
lastError = Marshal.GetLastWin32Error();
nRet = Convert.ToInt16(SetPrinter(hPrinter, 2, ptrPrinterInfo, 0));
// Error
if (nRet == 0)
return false;
if (hPrinter != IntPtr.Zero)
ClosePrinter(hPrinter);
return Convert.ToBoolean(nRet);
}
catch (Exception) { return false; }
}
public DEVMODE GetPrinterSettings(string PrinterName)
{
PrinterData PData = new PrinterData();
DEVMODE dm;
const int PRINTER_ACCESS_ADMINISTER = 0x4;
const int PRINTER_ACCESS_USE = 0x8;
const int PRINTER_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
PRINTER_ACCESS_ADMINISTER | PRINTER_ACCESS_USE);
PrinterValues.pDatatype = 0;
PrinterValues.pDevMode = 0;
PrinterValues.DesiredAccess = PRINTER_ALL_ACCESS;
nRet = Convert.ToInt32(OpenPrinter(PrinterName,
out hPrinter, PrinterValues));
GetPrinter(hPrinter, 2, IntPtr.Zero, 0, out nBytesNeeded);
Marshal.AllocCoTaskMem(nBytesNeeded);
ptrPrinterInfo = Marshal.AllocHGlobal(nBytesNeeded);
nRet = Convert.ToInt32(GetPrinter(hPrinter, 2, ptrPrinterInfo, nBytesNeeded, out nJunk));
pinfo = (PRINTER_INFO_2)Marshal.PtrToStructure(ptrPrinterInfo, typeof(PRINTER_INFO_2));
IntPtr Temp = new IntPtr();
if (pinfo.pDevMode == IntPtr.Zero)
{
IntPtr ptrZero = IntPtr.Zero;
sizeOfDevMode = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, ptrZero, ref ptrZero, 0);
ptrDM = Marshal.AllocCoTaskMem(sizeOfDevMode);
int i = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, ptrDM, ref ptrZero, DM_OUT_BUFFER);
pinfo.pDevMode = ptrDM;
}
intError = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, IntPtr.Zero, ref Temp, 0);
yDevModeData = Marshal.AllocHGlobal(intError);
intError = DocumentProperties(IntPtr.Zero, hPrinter, PrinterName, yDevModeData, ref Temp, 2);
dm = (DEVMODE)Marshal.PtrToStructure(yDevModeData, typeof(DEVMODE));
return dm;
}
}
If you get this error when building for AnyCPU or x64 you might find my answer here helpfull:
WinSpool OpenPrinter Access Denied - building for AnyCPU\x64
I have a class that is attempting to create a process from within a service using credentials provided.
When launching the process I am seeing an error Cannot create a file when that file already exists. What is causing this?
I've tried calling all types of executables, so I know it's not the process being created throwing this.
public class ProcessAsUser
{
static ProcessAsUser()
{
UserToken = IntPtr.Zero;
}
private static IntPtr UserToken { get; set; }
public int StartProcess(ProcessStartInfo processStartInfo)
{
UserToken = IntPtr.Zero;
LogInOtherUser(processStartInfo);
var startUpInfo = new Native.STARTUPINFO();
uint creationFlags = 0;
if (processStartInfo.CreateNoWindow) creationFlags |= Native.CREATE_NO_WINDOW;
var processInfo = new Native.PROCESS_INFORMATION();
bool processStarted = Native.CreateProcessAsUser(
UserToken, // user token
processStartInfo.FileName, // application name
processStartInfo.Arguments, // commandline
IntPtr.Zero, // process attributes
IntPtr.Zero, // thread attributes
true, // inherrit handle
creationFlags, // creation flags
IntPtr.Zero, // environment
processStartInfo.WorkingDirectory+"\\", // current directory
ref startUpInfo,
out processInfo
);
if (!processStarted)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
return 0;
}
int processId = (int)processInfo.dwProcessId;
Native.CloseHandle(processInfo.hProcess);
Native.CloseHandle(processInfo.hThread);
ProcessId = processId;
return ProcessId;
}
public int ProcessId;
private static void LogInOtherUser(ProcessStartInfo processStartInfo)
{
if (UserToken == IntPtr.Zero)
{
var tempUserToken = IntPtr.Zero;
var password = SecureStringToString(processStartInfo.Password);
bool loginResult = Native.LogonUser(processStartInfo.UserName, processStartInfo.Domain, password,
Native.LOGON32_LOGON_BATCH, Native.LOGON32_PROVIDER_DEFAULT,
ref tempUserToken);
if (loginResult)
{
UserToken = tempUserToken;
}
else
{
Native.CloseHandle(tempUserToken);
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
private static String SecureStringToString(SecureString value)
{
var stringPointer = Marshal.SecureStringToBSTR(value);
try
{
return Marshal.PtrToStringBSTR(stringPointer);
}
finally
{
Marshal.FreeBSTR(stringPointer);
}
}
public static void ReleaseUserToken()
{
Native.CloseHandle(UserToken);
}
}
internal class Native
{
internal const int LOGON32_LOGON_INTERACTIVE = 2;
internal const int LOGON32_LOGON_BATCH = 4;
internal const int LOGON32_PROVIDER_DEFAULT = 0;
public const int DUPLICATE_SAME_ACCESS = 2;
public const int CREATE_NO_WINDOW = 0x08000000;
public const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
[StructLayout(LayoutKind.Sequential)]
internal class PROCESS_INFORMATION
{
public IntPtr hProcess = IntPtr.Zero;
public IntPtr hThread = IntPtr.Zero;
public uint dwProcessId = 0;
public uint dwThreadId = 0;
}
[StructLayout(LayoutKind.Sequential)]
internal class STARTUPINFO
{
public int cb;
public string lpReserved;
public string lpDesktop = string.Empty;
public string lpTitle;
public int dwX = 0;
public int dwY = 0;
public int dwXSize = 0;
public int dwYSize = 0;
public int dwXCountChars = 0;
public int dwYCountChars = 0;
public int dwFillAttribute = 0;
public int dwFlags = 0;
public short wShowWindow = 0;
public short cbReserved2 = 0;
public IntPtr lpReserved2 = IntPtr.Zero;
public IntPtr hStdInput = IntPtr.Zero;
public IntPtr hStdOutput = IntPtr.Zero;
public IntPtr hStdError = IntPtr.Zero;
public STARTUPINFO()
{
cb = Marshal.SizeOf(this);
}
}
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
public SECURITY_ATTRIBUTES()
{
nLength = Marshal.SizeOf(this);
}
public int nLength;
public IntPtr lpSecurityDescriptor = IntPtr.Zero;
public bool bInheritHandle;
}
[DllImport("advapi32.dll", EntryPoint = "LogonUserW", SetLastError = true, CharSet = CharSet.Unicode,
CallingConvention = CallingConvention.StdCall)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUserA", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern bool CreateProcessAsUser(
IntPtr hToken,
[MarshalAs(UnmanagedType.LPStr)] string lpApplicationName,
[MarshalAs(UnmanagedType.LPStr)] string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandle,
uint dwCreationFlags,
IntPtr lpEnvironment,
[MarshalAs(UnmanagedType.LPStr)] string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll", EntryPoint = "CloseHandle", SetLastError = true, CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
internal static extern bool CloseHandle(IntPtr handle);
}
i have a project about USB disk.i have achieved eject the usb disk in my code.but then i want to know how to reload it? Can anyone give me some suggestion.
better an example!thx
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
private void btnenable_Click(object sender, EventArgs e)
{
const string keyName = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR";
// int tLong = (int )Registry.GetValue(keyName, "Start",0);
Registry.SetValue(keyName, "Start", "00000003");
MessageBox.Show("USB MassStorage Enabled");
}
private void btndisable_Click(object sender, EventArgs e)
{
const string keyName = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR";
// int tLong = (int )Registry.GetValue(keyName, "Start",0);
Registry.SetValue(keyName, "Start", "00000004");
MessageBox.Show("USB MassStorage Disabled");
}
I have resolved this question in this way,flow is my code:
win32.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace SystemDevices
{
[StructLayout(LayoutKind.Sequential)]
public struct SP_BROADCAST_HANDLE
{
public int dbch_size;
public int dbch_devicetype;
public int dbch_reserved;
public IntPtr dbch_handle;
public IntPtr dbch_hdevnotify;
public Guid dbch_eventguid;
public long dbch_nameoffset;
public byte dbch_data;
public byte dbch_data1;
}
[StructLayout(LayoutKind.Sequential)]
public class DEV_BROADCAST_DEVICEINTERFACE
{
public int dbcc_size;
public int dbcc_devicetype;
public int dbcc_reserved;
}
[StructLayout(LayoutKind.Sequential)]
public class SP_DEVINFO_DATA
{
public int cbSize;
public Guid classGuid;
public int devInst;
public IntPtr reserved;
};
[StructLayout(LayoutKind.Sequential)]
public class SP_DEVINSTALL_PARAMS
{
public int cbSize;
public int Flags;
public int FlagsEx;
public IntPtr hwndParent;
public IntPtr InstallMsgHandler;
public IntPtr InstallMsgHandlerContext;
public IntPtr FileQueue;
public IntPtr ClassInstallReserved;
public int Reserved;
[MarshalAs(UnmanagedType.LPTStr)]
public string DriverPath;
};
[StructLayout(LayoutKind.Sequential)]
public class SP_PROPCHANGE_PARAMS
{
public SP_CLASSINSTALL_HEADER ClassInstallHeader = new SP_CLASSINSTALL_HEADER();
public int StateChange;
public int Scope;
public int HwProfile;
};
[StructLayout(LayoutKind.Sequential)]
public class SP_CLASSINSTALL_HEADER
{
public int cbSize;
public int InstallFunction;
};
public class Win32
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, DEV_BROADCAST_DEVICEINTERFACE NotificationFilter, UInt32 Flags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern UInt32 UnregisterDeviceNotification(IntPtr hHandle);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
[MarshalAs(UnmanagedType.LPStr)]String Enumerator, IntPtr hwndParent, Int32 Flags);
[DllImport("setupapi.dll")]
public static extern IntPtr SetupDiGetClassDevsEx(ref Guid ClassGuid,
[MarshalAs(UnmanagedType.LPStr)]String Enumerator,
IntPtr hwndParent, Int32 Flags, IntPtr DeviceInfoSet,
[MarshalAs(UnmanagedType.LPStr)]String MachineName,
IntPtr Reserved);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern Boolean SetupDiEnumDeviceInfo(IntPtr lpInfoSet, Int32 dwIndex, SP_DEVINFO_DATA devInfoData);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern Boolean SetupDiGetDeviceRegistryProperty(IntPtr lpInfoSet, SP_DEVINFO_DATA DeviceInfoData, UInt32 Property,
UInt32 PropertyRegDataType, StringBuilder PropertyBuffer, UInt32 PropertyBufferSize, IntPtr RequiredSize);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern Boolean SetupDiSetClassInstallParams(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, SP_PROPCHANGE_PARAMS ClassInstallParams, int ClassInstallParamsSize);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern Boolean SetupDiCallClassInstaller(UInt32 InstallFunction, IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern Boolean SetupDiClassNameFromGuid(ref Guid ClassGuid, StringBuilder className, Int32 ClassNameSize, ref Int32 RequiredSize);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern Boolean SetupDiGetClassDescription(ref Guid ClassGuid, StringBuilder classDescription, Int32 ClassDescriptionSize, ref Int32 RequiredSize);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern Boolean SetupDiGetDeviceInstanceId(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, StringBuilder DeviceInstanceId, Int32 DeviceInstanceIdSize, ref Int32 RequiredSize);
public const int DIGCF_ALLCLASSES = (0x00000004);
public const int DIGCF_PRESENT = (0x00000002);
public const int INVALID_HANDLE_VALUE = -1;
public const int SPDRP_DEVICEDESC = (0x00000000);
public const int MAX_DEV_LEN = 200;
public const int DEVICE_NOTIFY_WINDOW_HANDLE = (0x00000000);
public const int DEVICE_NOTIFY_SERVICE_HANDLE = (0x00000001);
public const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = (0x00000004);
public const int DBT_DEVTYP_DEVICEINTERFACE = (0x00000005);
public const int DBT_DEVNODES_CHANGED = (0x0007);
public const int WM_DEVICECHANGE = (0x0219);
public const int DIF_PROPERTYCHANGE = (0x00000012);
public const int DICS_FLAG_GLOBAL = (0x00000001);
public const int DICS_FLAG_CONFIGSPECIFIC = (0x00000002);
public const int DICS_ENABLE = (0x00000001);
public const int DICS_DISABLE = (0x00000002);
public static bool StateChange(bool Enable, int SelectedItem, IntPtr DevInfo)
{
bool result = false;
SP_DEVINFO_DATA devInfoData = new SP_DEVINFO_DATA(); ;
devInfoData.cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
if (true == SetupDiEnumDeviceInfo(DevInfo, SelectedItem, devInfoData))
{
SP_PROPCHANGE_PARAMS pcp = new SP_PROPCHANGE_PARAMS(); ;
pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(SP_CLASSINSTALL_HEADER));
pcp.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
pcp.Scope = DICS_FLAG_GLOBAL;
pcp.StateChange = (Enable ? DICS_ENABLE : DICS_DISABLE);
if (true == SetupDiSetClassInstallParams(DevInfo, devInfoData, pcp, Marshal.SizeOf(pcp)))
{
if (true == SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, DevInfo, devInfoData))
{
result = true;
}
}
}
return result;
}
public static String GetClassNameFromGuid(Guid guid)
{
String result = String.Empty;
StringBuilder className = new StringBuilder();
Int32 iRequiredSize = 0;
Int32 iSize = 0;
bool b = SetupDiClassNameFromGuid(ref guid, className, iSize, ref iRequiredSize);
className = new StringBuilder(iRequiredSize);
iSize = iRequiredSize;
b = SetupDiClassNameFromGuid(ref guid, className, iSize, ref iRequiredSize);
if (true == b)
{
result = className.ToString();
}
return result;
}
public static String GetClassDescriptionFromGuid(Guid guid)
{
String result = String.Empty;
StringBuilder classDesc = new StringBuilder(0);
Int32 iRequiredSize = 0;
Int32 iSize = 0;
bool b = SetupDiGetClassDescription(ref guid, classDesc, iSize, ref iRequiredSize);
classDesc = new StringBuilder(iRequiredSize);
iSize = iRequiredSize;
b = SetupDiGetClassDescription(ref guid, classDesc, iSize, ref iRequiredSize);
if (true == b)
{
result = classDesc.ToString();
}
return result;
}
public static String GetDeviceInstanceId(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData)
{
String result = String.Empty;
StringBuilder id = new StringBuilder(0);
Int32 iRequiredSize = 0;
Int32 iSize = 0;
bool b = SetupDiGetDeviceInstanceId(DeviceInfoSet, DeviceInfoData, id, iSize, ref iRequiredSize);
id = new StringBuilder(iRequiredSize);
iSize = iRequiredSize;
b = SetupDiGetDeviceInstanceId(DeviceInfoSet, DeviceInfoData, id, iSize, ref iRequiredSize);
if (true == b)
{
result = id.ToString();
}
return result;
}
}
}
in the win32.cs there is some function to control the hardware.
function StateChange(bool Enable, int SelectedItem, IntPtr DevInfo) is used to control the hardware start or stop.
there are three Parameters.when the Enable is true,this function makes the hardware whos id is SelectedItem start,if false stop.i get the id in this code:
Guid classGuid = Guid.Empty;
IntPtr hDevInfo = Win32.SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, Win32.DIGCF_ALLCLASSES | Win32.DIGCF_PRESENT);
if (hDevInfo.ToInt32() == Win32.INVALID_HANDLE_VALUE)
{
Console.WriteLine("read hardware information error");
}
else
{
int i = 0;
StringBuilder deviceName = new StringBuilder();
deviceName.Capacity = Win32.MAX_DEV_LEN;
do
{
SP_DEVINFO_DATA devInfoData = new SP_DEVINFO_DATA();
devInfoData.cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
devInfoData.classGuid = Guid.Empty;
devInfoData.devInst = 0;
devInfoData.reserved = IntPtr.Zero;
bool result = Win32.SetupDiEnumDeviceInfo(hDevInfo, i, devInfoData);
if (false == result)
{
break;
}
Console.WriteLine("Device: {0}", i);
Console.WriteLine("\tGuid={0}", devInfoData.classGuid);
Console.WriteLine("\tName={0}", Win32.GetClassNameFromGuid(devInfoData.classGuid));
Console.WriteLine("\tDescription={0}", Win32.GetClassDescriptionFromGuid(devInfoData.classGuid));}
There is a tool (devcon) available from Microsoft that can be used to achieve the functionality of the device manager.
The following command is used to remove a specific device (Assuming your device name is Kingston)
> devcon remove *Kingston*
This causes the device to be disabled. So it is no longer available.
The command rescan enables the device.
> devcon rescan
You can execute this command through the Process.Start() method.
This does not work with devices that have marked for 'Safe Removal'