using System;
using System
using System
namespace Sample
{
class App
{
static void Main(string[] args)
{
Console
Console
int pt =
try
{
pt=Int
}
catch(Exception e)
{
Console
return;
}
PRINTER_ENUM printerKind = GetPrinterConType(pt);
PrinterSearcher p = new PrinterSearcher();
PrinterSearcher
foreach(PrinterSearcher
{
Console
pi
}
}
static PRINTER_ENUM GetPrinterConType(int ins)
{
switch(ins)
{
case
return PRINTER_ENUM
case
return PRINTER_ENUM
case
return PRINTER_ENUM
case
return PRINTER_ENUM
case
return PRINTER_ENUM
case
return PRINTER_ENUM
case
return PRINTER_ENUM
default:
return PRINTER_ENUM
}
}
}
#region 打印機位置狀態枚舉 PRINTER_ENUM
public enum PRINTER_ENUM
{
DEFAULT =
LOCAL =
CONNECTIONS =
NAME =
REMOTE =
SHARED =
NETWORK =
}
#endregion
#region 異常派生 EnumPrinterException
[Serializable]
public class EnumPrinterException: ApplicationException
{
public EnumPrinterException() { }
public EnumPrinterException (string message): base(message) { }
public EnumPrinterException (string message
base(message
protected EnumPrinterException (SerializationInfo info
StreamingContext context) : base(info
{ }
}
#endregion
//加上這個屬性可以按導出到非托管對像的順序排序
[StructLayout(LayoutKind
public class PRINTER_INFO_
{
public int flags;
public IntPtr pDescription;
public IntPtr pName;
public IntPtr pComment;
}
public class PrinterSearcher
{
#region Search
public PrinterInfo[] Search(PRINTER_ENUM printerKind)
{
PrinterInfo[] pInfo = new PrinterInfo[
uint iNeeded =
IntPtr printers = IntPtr
if (!EnumPrinters(printerKind
{
//返回由上一個非托管函數返回的錯誤代碼
//DllImport屬性中SetLastError=true 標志的平台調用來調用的
int err = Marshal
if (err != Win
ThrowEnumPrinterException();
}
iSize = iNeeded;
if (iNeeded !=
{
try
{
//使用AllocHGlobal分配非托管內塊
printers = Marshal
//如果調用不成功拋出異常
if (!EnumPrinters(printerKind
{
ThrowEnumPrinterException();
}
else
{
pInfo = GetPrinterInfoFromMemory(printers
}
}
finally
{
//釋放分配的內存塊
if (printers != IntPtr
Marshal
}
}
return pInfo;
}
#endregion
#region PrinterInfo
public struct PrinterInfo
{
public string Name;
public string Description;
public string Comment;
}
public sealed class Win
{
private Win
public const int ERROR_INSUFFICIENT_BUFFER =
}
#endregion
#region EnumPrinters
[DllImport(
[return: MarshalAs(UnmanagedType
private static extern bool EnumPrinters ([MarshalAs(UnmanagedType
[MarshalAs(UnmanagedType
uint iLevel
IntPtr pPrinterDesc
uint iSize
[MarshalAs(UnmanagedType
[MarshalAs(UnmanagedType
);
#endregion
#region GetPrinterInfoFromMemory
private PrinterInfo[] GetPrinterInfoFromMemory(IntPtr prInfo
{
PRINTER_INFO_
PrinterInfo[] pInfo = new PrinterInfo[numPrinters];
for(int i =
{
//把數據從非托管內存傳送到到托管內存
Marshal
pInfo[i]
pInfo[i]
pInfo[i]
prInfo = new IntPtr(prInfo
}
return pInfo;
}
private void ThrowEnumPrinterException()
{
throw new EnumPrinterException(string
Marshal
}
#endregion
}
}
From:http://tw.wingwit.com/Article/program/Delphi/201311/8424.html