我想要在計算機和網絡上安裝所有打印機名稱。 我在下面使用這些函數來獲取所有打印機的列表。所有這些功能。在控制檯和窗體應用程序中正常工作,我可以獲取所有打印機的列表,但是當我嘗試使用這些功能時。在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();
}
「我的服務下,LocalSystem帳戶工作」 - 那麼它就會出現任何網絡打印機爲您的計算機帳戶 - 您的計算機帳戶權限訪問任何這些打印機? –
是的,我有權限訪問所有。 – mburakerbay
**你**有,但你的**機**? –