//返回由上一个非托管函数返回的错误代码,该函数是使用设置了 - //DllImport属性中SetLastError=true 标志的平台调用来调用的 int err = Marshal.GetLastWin32Error(); if (err != Win32Error.ERROR_INSUFFICIENT_BUFFER) ThrowEnumPrinterException(); } iSize = iNeeded; if (iNeeded != 0) { try { //使用AllocHGlobal分配非托管内块 printers = Marshal.AllocHGlobal(new IntPtr(iSize)); //如果调用不成功抛出异常 if (!EnumPrinters(printerKind, String.Empty,1,printers, iSize, ref iNeeded, ref iReturned) ) { ThrowEnumPrinterException(); } else { pInfo = GetPrinterInfoFromMemory(printers, iReturned); } } finally { //释放分配的内存块 if (printers != IntPtr.Zero) Marshal.FreeHGlobal(printers); } } return pInfo; } #endregion #region PrinterInfo public struct PrinterInfo { public string Name; public string Description; public string Comment; } public sealed class Win32Error { private Win32Error() {} public const int ERROR_INSUFFICIENT_BUFFER = 122; } #endregion #region EnumPrinters [DllImport("winspool.drv", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] |