检索所有可用打印机驱动程序的列表(例如“添加打印机向导”)

时间:2012-11-05 12:17:01

标签: c# printing driver

在c#中,我将获得正在运行的系统上安装的所有打印机驱动程序的列表,例如Windows "add printer" wizard

我已经能够列出已安装的打印机,但如何列出系统上可用的驱动程序?

2 个答案:

答案 0 :(得分:0)

也许这可以帮到你: http://msdn.microsoft.com/en-us/library/system.drawing.printing.printersettings.installedprinters.aspx 通过这种方式,您可以安装打印机。

答案 1 :(得分:0)

此代码枚举已安装的打印机驱动程序:

public struct DRIVER_INFO_2
{
    public uint cVersion;
    [MarshalAs(UnmanagedType.LPTStr)] public string pName;
    [MarshalAs(UnmanagedType.LPTStr)] public string pEnvironment;
    [MarshalAs(UnmanagedType.LPTStr)] public string pDriverPath;
    [MarshalAs(UnmanagedType.LPTStr)] public string pDataFile;
    [MarshalAs(UnmanagedType.LPTStr)] public string pConfigFile;
}


public static class EnumeratePrinterDriverNames
{
    [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern int EnumPrinterDrivers(String pName, String pEnvironment, uint level, IntPtr pDriverInfo,
        uint cdBuf, ref uint pcbNeeded, ref uint pcRetruned);

    public static IEnumerable<string> Enumerate()
    {
        const int ERROR_INSUFFICIENT_BUFFER = 122;

        uint needed = 0;
        uint returned = 0;
        if (EnumPrinterDrivers(null, null, 2, IntPtr.Zero, 0, ref needed, ref returned) != 0)
        {
            //succeeds, but shouldn't, because buffer is zero (too small)!
            throw new ApplicationException("EnumPrinters should fail!");
        }

        int lastWin32Error = Marshal.GetLastWin32Error();
        if (lastWin32Error != ERROR_INSUFFICIENT_BUFFER)
        {
            throw new Win32Exception(lastWin32Error);
        }

        IntPtr address = Marshal.AllocHGlobal((IntPtr) needed);
        try
        {
            if (EnumPrinterDrivers(null, null, 2, address, needed, ref needed, ref returned) == 0)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            var type = typeof (DRIVER_INFO_2);
            IntPtr offset = address;
            int increment = Marshal.SizeOf(type);

            for (uint i = 0; i < returned; i++)
            {
                var di = (DRIVER_INFO_2) Marshal.PtrToStructure(offset, type);
                offset += increment;

                yield return di.pName;
            }
        }
        finally
        {
            Marshal.FreeHGlobal(address);
        }
    }
}