C#調用WIN32API系列二列舉局網內共享打印機
C#通過調用WIN32API可以實現非常強大的功能,本文將著重講述如何通過調用WIN32API實現列舉局域網絡內所有共享的打印機。
首先我們看看EnumPrinters函數的定義
BOOL EnumPrinters(
DWord Flags, // printer object types
LPTSTR Name, // name of printer object
DWord Level, // information level
LPBYTE pPrinterEnum, // printer information buffer
DWord cbBuf, // size of printer information buffer
LPDWord pcbNeeded, // bytes received or required
LPDWord pcReturned // number of printers enumerated
);
這個api有幾個返回參數, 其中最重要的是pPrinterEnum所指的緩沖區中,是一個
PRINTER_INFO_N的結構數組, 這裡N根據Level參數而變化, 這裡我們用的是1, 所以用到的結構是
typedef struct _PRINTER_INFO_1 {
DWord Flags;
LPTSTR pDescription;
LPTSTR pName;
LPTSTR pComment;
} PRINTER_INFO_1
C#要調用API首先要引入動態庫,EnumPrinters在winspool.drv這個動態庫中。引入語句如下
[DllImport("winspool.drv", CharSet=CharSet.Auto)]
然後是定義PRINTER_INFO_1結構
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
struct PRINTER_INFO_1
{
int flags;
[MarshalAs(UnmanagedType.LPTStr)]
public string pDescription;
[MarshalAs(UnmanagedType.LPTStr)]
public string pName;
[MarshalAs(UnmanagedType.LPTStr)]
public string pComment;
}
好了,全部的源代碼如下:
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Drawing.Printing;
public class QuickTest {
[DllImport("winspool.drv", CharSet=CharSet.Auto)]
static extern bool EnumPrinters(int flags, string name, int level, IntPtr pPrinterEnum,
int cbBuf, out int pcbNeeded, out int pcReturned);
private const int PRINTER_ENUM_NETWORK= 0x00000040;
private const int PRINTER_ENUM_LOCAL= 0x00000002;
private const int PRINTER_ENUM_REMOTE = 0x00000010;
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
struct PRINTER_INFO_1
{
int flags;
[MarshalAs(UnmanagedType.LPTStr)]
public string pDescription;
[MarshalAs(UnmanagedType.LPTStr)]
public string pName;
[MarshalAs(UnmanagedType.LPTStr)]
public string pComment;
}
public void EnumeratePrintersWin()
{
bool Success;
int cbRequired;
int nEntrIEs;
IntPtr outb = IntPtr.Zero;
Success = EnumPrinters(PRINTER_ENUM_NETWORK | PRINTER_ENUM_LOCAL | PRINTER_ENUM_REMOTE, null , 1, outb, 0, out cbRequired, out nEntrIEs);
outb = Marshal.AllocHGlobal(cbRequired);
Success = EnumPrinters(PRINTER_ENUM_NETWORK | PRINTER_ENUM_LOCAL | PRINTER_ENUM_REMOTE, null , 1, outb, cbRequired, out cbRequired, out nEntrIEs);
PRINTER_INFO_1[] portsArray = new PRINTER_INFO_1[cbRequired];
IntPtr current = outb;
try {
for (int i=0; i
{
portsArray[i] = (PRINTER_INFO_1) Marshal.PtrToStructure(current,
typeof(PRINTER_INFO_1));
current=(IntPtr)((int)current+Marshal.SizeOf(typeof(PRINTER_INFO_1)));
Console.WriteLine(i+": \n"+portsArray[i].pName+"\n"+portsArray[i].pDescription+"\n"+portsArray[i].pComment+"\n");
}
}
catch (Exception) {
//Console.WriteLine(exp.StackTrace);
}
Marshal.FreeHGlobal(outb);
}
public QuickTest () {
}
public static void Main() {
QuickTest qt = new QuickTest();
qt.EnumeratePrintersWin();
}
}