近来对打印机做了一些研究,因为某些需要所以想对打印机状态进行查询,在此留下心得。
有些打印机厂家会提供专门的SDK供使用者查询打印机状态,但通常情况下,在C#中还是选择调用WIN32 api来进行打印机状态的监控。下面进入正题
调用WIN32 API 需要先声明命名空间
using System.Runtime.InteropServices;
[DllImport("winspool.drv", CharSet = CharSet.Auto)]
public static extern bool OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);//打开打印机
[DllImport("winspool.drv", CharSet = CharSet.Auto)]
public static extern bool ClosePrinter(IntPtr hPrinter);//关闭
[DllImport("winspool.drv", CharSet = CharSet.Auto)]
public static extern int EnumJobs(IntPtr hPrinter, int FirstJob, int NoJobs, int Level, IntPtr pInfo, int cdBuf,out int pcbNeeded, out int pcReturned);//状态获取
然后是调用
IntPtr handle;
int FirstJob = 0;
int NumJobs = 127;
int pcbNeeded;
int pcReturned;
int test;
bool settest=
// open printer
OpenPrinter(printerToPeek, out handle, IntPtr.Zero);
get num bytes required, here we assume the maxt job for the printer quest is 128 (0..127)
EnumJobs(handle, FirstJob, NumJobs, 1, IntPtr.Zero, 0, out pcbNeeded, out pcReturned);
// allocate unmanaged memory
IntPtr pData = Marshal.AllocHGlobal(pcbNeeded);
// get structs
EnumJobs(handle, FirstJob, NumJobs, 1, pData, pcbNeeded, out pcbNeeded, out pcReturned);
判断EnumJobs函数的返回或者pcbNeeded的数值可以判断打印机状态,正在就绪是0,即pcbNeeded==0?正在就绪:其他状态。其他的未进行研究。
参考: