2013-04-03 112 views
0

我想要在計算機和網絡上安裝所有打印機名稱。 我在下面使用這些函數來獲取所有打印機的列表。所有這些功能。在控制檯和窗體應用程序中正常工作,我可以獲取所有打印機的列表,但是當我嘗試使用這些功能時。在Windows服務中,我只能安裝在帶有網絡的計算機上。我的服務也在LocalSystem帳戶下工作。如何在windows服務中獲取所有打印機名稱?

函數功能1:

 WinsPool.PrinterEnumFlags Flags = WinsPool.PrinterEnumFlags.PRINTER_ENUM_CONNECTIONS | WinsPool.PrinterEnumFlags.PRINTER_ENUM_LOCAL; 
     const int ERROR_INSUFFICIENT_BUFFER = 122; 
     uint cbNeeded = 0; 
     uint cReturned = 0; 
     if (WinsPool.EnumPrinters(Flags, null, 2, IntPtr.Zero, 0, ref cbNeeded, ref cReturned)) 
     { 
      return null; 
     } 
     int lastWin32Error = Marshal.GetLastWin32Error(); 
     if (lastWin32Error == ERROR_INSUFFICIENT_BUFFER) 
     { 
      IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded); 
      if (WinsPool.EnumPrinters(Flags, null, 2, pAddr, cbNeeded, ref cbNeeded, ref cReturned)) 
      { 
       WinsPool.PRINTER_INFO_2[] printerInfo2 = new WinsPool.PRINTER_INFO_2[cReturned]; 
       int offset = pAddr.ToInt32(); 
       Type type = typeof(WinsPool.PRINTER_INFO_2); 
       int increment = Marshal.SizeOf(type); 
       for (int i = 0; i < cReturned; i++) 
       { 
        printerInfo2[i] = (WinsPool.PRINTER_INFO_2)Marshal.PtrToStructure(new IntPtr(offset), type); 
        string printerName = printerInfo2[i].pPrinterName; 
        offset += increment; 
       } 
       Marshal.FreeHGlobal(pAddr); 
      } 
      lastWin32Error = Marshal.GetLastWin32Error(); 
     } 

函數功能2:

 foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) 
     { 
      string printerName = printer; 
     } 

Func鍵3:

  ManagementObjectSearcher searcher = 
       new ManagementObjectSearcher("root\\CIMV2", 
       "SELECT * FROM Win32_Printer"); 

      foreach (ManagementObject queryObj in searcher.Get()) 
      { 
       string printerName = queryObj["Name"].ToString(); 
      } 
+0

「我的服務下,LocalSystem帳戶工作」 - 那麼它就會出現任何網絡打印機爲您的計算機帳戶 - 您的計算機帳戶權限訪問任何這些打印機? –

+0

是的,我有權限訪問所有。 – mburakerbay

+0

**你**有,但你的**機**? –

回答

1

打印機通常安裝到一個特定的Windows帳戶,因此只有以該帳戶登錄時才能看到它們。對於需要訪問打印機的Windows服務,通常將其作爲所需打印機可見的指定帳戶運行,即不要將其作爲LocalSystem運行。

1

下面是如何開始:

public partial class Service : ServiceBase 
{ 
    List<string> printers = new List<string>(); 
    public Service() 
    { 
     InitializeComponent(); 
    } 

    protected override void OnStart(string[] args) 
    { 
     getPrinters(); 
    } 

    private void getPrinters() 
    { 
     foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters) 
     { 
      printers.Add(printer); 
     } 

    } 

    static void Main() 
    { 
     (new Service()).OnStart(null); // allows easy debugging of OnStart() 
    } 
相關問題