2012-11-05 12 views
5

In C# vorrei ottenere un elenco di tutti i driver di stampa installati su sistema in esecuzione, come Windows "add printer" wizard:recuperare l'elenco di tutti i driver di stampante disponibili (come l'installazione guidata stampante)

Sono stato in grado di elencare stampanti già installate, ma come faccio ad elencare i driver disponibili sul sistema?

+0

Questa procedura guidata * non * Lista installato i driver di stampa, include driver che * possa * essere installato. Questo tipo di funzionalità è nascosto nell'API di installazione. Molto difficile da usare da .NET, il pinvoke è cattivo. Ed è * non * una semplice API da utilizzare in generale. http://msdn.microsoft.com/en-us/library/windows/hardware/ff553567%28v=vs.85%29.aspx –

+0

Grazie mille per la risposta. Penso che preferirei evitare ... –

risposta

0

Questo codice enumera i driver di stampa installati:

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); 
     } 
    } 
} 
Problemi correlati