我想在计算机和网络上安装所有打印机名称。我在下面使用这些功能来获取所有打印机的列表。所有这些功能。在控制台和表单应用程序中正常工作,我可以获得所有打印机的列表,但是当我尝试使用这些功能时。在 Windows 服务中,我只能安装在没有网络的计算机上。还有我的服务在LocalSystem
账户下工作。
功能 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;
}
功能 3:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_Printer");
foreach (ManagementObject queryObj in searcher.Get())
{
string printerName = queryObj["Name"].ToString();
}