1

我正在用 C# 编写一个将在用户 PC 上运行的应用程序,我只想列出 Windows“设备和打印机”控制面板中显示的设备,例如显示器、键盘、鼠标、扬声器等。

我可以使用 WMI 来提取所有设备的列表,但是有没有办法只提取那些显示在控制面板的那部分而不是完整列表中的设备?

我在网上搜索并没有发现任何与此相关的内容,我什至找不到设备出现在该列表中的标准是什么。

是否可以访问该列表中显示的那些设备的列表,或者,如果没有,是否有一个过滤器可以应用于仅显示这些设备的完整列表?

提前致谢

4

1 回答 1

2

我使用 p/invoke 和 COM 互操作通过枚举其中的 shell 项Microsoft.DevicesAndPrinters并通过确保其中PKEY_Devices_CategoryIds包含以PrintFax.

没有办法将必要的互操作定义归结为适合答案,但这是我用来枚举显示名称、DEVMODE 名称和任何大小的图像的逻辑:

public sealed class PrinterInfo
{
    public string IdName { get; }
    public string DisplayName { get; }
    public Bitmap Image { get; }

    private PrinterInfo(string idName, string displayName, Bitmap image)
    {
        IdName = idName;
        DisplayName = displayName;
        Image = image;
    }

    public static IReadOnlyList<PrinterInfo> GetInstalledPrinterNamesAndImages(Size imageSize)
    {
        var r = new List<PrinterInfo>();

        using (var folderIdList = CreateDevicesAndPrintersIDL())
        {
            var folder = GetShellFolder(folderIdList);
            var enumerator = folder.EnumObjects(IntPtr.Zero, SHCONTF.NONFOLDERS);

            for (;;)
            {
                // If you request more than are left, actualCount is 0, so we'll do one at a time.
                var next = enumerator.Next(1, out var relativeIdList, out var actualCount);
                next.ThrowIfError();
                if (next == HResult.False || actualCount != 1) break; // printerChild is junk

                using (relativeIdList)
                using (var absoluteIdList = ILCombine(folderIdList, relativeIdList))
                {
                    var shellItem = GetShellItem(absoluteIdList);
                    var idName = GetPrinterFriendlyNameIfPrinter(shellItem);
                    if (idName != null)
                        r.Add(new PrinterInfo(idName, GetDisplayName(shellItem), GetImage(shellItem, imageSize)));
                }
            }
        }

        return r;
    }

    private static ItemIdListSafeHandle CreateDevicesAndPrintersIDL()
    {
        SHGetKnownFolderIDList(FOLDERID.ControlPanelFolder, KF_FLAG.DEFAULT, IntPtr.Zero, out var controlPanelIdList).ThrowIfError();
        using (controlPanelIdList)
        {
            GetShellFolder(controlPanelIdList).ParseDisplayName(IntPtr.Zero, null, "::{A8A91A66-3A7D-4424-8D24-04E180695C7A}", IntPtr.Zero, out var childDevicesAndPriversIdList, IntPtr.Zero);
            using (childDevicesAndPriversIdList)
                return ILCombine(controlPanelIdList, childDevicesAndPriversIdList);
        }
    }

    private static string GetPrinterFriendlyNameIfPrinter(IShellItem2 shellItem)
    {
        // Devices_PrimaryCategory returns "Printers" for printers and faxes on Windows 10 but "Printers and faxes" on Windows 7.
        using (var categoryIds = new PropVariantSafeHandle())
        {
            shellItem.GetProperty(PKEY.Devices_CategoryIds, categoryIds).ThrowIfError();
            if (!categoryIds.ToStringVector().Any(id => id.StartsWith("PrintFax", StringComparison.OrdinalIgnoreCase)))
                return null;
        }

        // The canonical or "friendly name" needed to match the devmode
        // https://blogs.msdn.microsoft.com/asklar/2009/10/21/getting-the-printer-friendly-name-from-the-device-center-shell-folder/
        // PKEY_Devices_InterfacePaths doesn't seem to ever be found, but PKEY_Devices_FriendlyName works so...
        shellItem.GetString(PKEY.Devices_FriendlyName, out var friendlyName).ThrowIfError();
        return friendlyName.ReadAndFree();
    }

    private static string GetDisplayName(IShellItem2 shellItem)
    {
        return shellItem.GetDisplayName(SIGDN.NORMALDISPLAY).ReadAndFree();
    }

    private static Bitmap GetImage(IShellItem2 shellItem, Size imageSize)
    {
        return ((IShellItemImageFactory)shellItem).GetImage(new POINT(imageSize.Width, imageSize.Height), SIIGBF.SIIGBF_BIGGERSIZEOK)
            .CopyAndFree(); // Bitmap.FromHbitmap is useless with alpha, so make a copy
    }


    private static IShellFolder GetShellFolder(ItemIdListSafeHandle itemIdList)
    {
        SHBindToObject(IntPtr.Zero, itemIdList, null, typeof(IShellFolder).GUID, out var objShellFolder).ThrowIfError();
        return (IShellFolder)objShellFolder;
    }

    private static IShellItem2 GetShellItem(ItemIdListSafeHandle itemIdList)
    {
        SHCreateItemFromIDList(itemIdList, typeof(IShellItem2).GUID, out var objShellItem).ThrowIfError();
        return (IShellItem2)objShellItem;
    }
}

(C# 7)

这是您可以编译的完整演示:https ://github.com/jnm2/example-devices-and-printers/tree/master/src

对于不需要 ValueTuple 的 C# 6 版本,请参阅https://github.com/jnm2/example-devices-and-printers/tree/master/src-csharp6

我很乐意回答任何问题。

于 2017-11-14T01:20:00.523 回答