一、使用API函数之前,首先查阅MSDN或者其他权威资料,得到函数的具体介绍
EnumPorts
The EnumPorts function enumerates the ports that are available for printing on a specified server.(此函数枚举出了指定的服务器上面的可用打印机设备)
BOOL EnumPorts(
LPTSTR pName, // pointer to server name(指向服务器名称的指针)
DWORD Level, // specifies type of port info structure(打印机信息结构体的具体类型)
LPBYTE pPorts, // pointer to buffer to receive array of port
// info. Structures(指向打印机信息结构数组)
DWORD cbBuf, // specifies size, in bytes, of buffer(确定数组缓存的具体字节大小)
LPDWORD pcbNeeded, // pointer to number of bytes stored into
// buffer (or required buffer size)(指向数组字节大小存储)
LPDWORD pcReturned // pointer to number of PORT_INFO_*.
// structures stored into buffer(指向打印机结构数目的指针)
);
其中关于打印机信息的结构类型亦可参照MSDN文档,我们此处参照PORT_INFO_2
PORT_INFO_2
The PORT_INFO_2 structure identifies a supported printer port.
typedef struct _PORT_INFO_2 { // pi2
LPSTR pPortName;
LPSTR pMonitorName
LPSTR pDescription;
DWORD fPortType;
DWORD Reserved;
} PORT_INFO_2;
二、使用API
//需要加上头文件#include "winspool.h" const LPTSTR pName = NULL; // pointer to server name此处为空,就是本机 const DWORD Level = 2; // specifies type of port info structure,即PORT_INFO_2 LPBYTE port=0; // pointer to buffer to receive array of port info. structures DWORD cbBuf=0; // specifies size, in bytes, of buffer DWORD pcbNeeded=0; // pointer to number of bytes stored into buffer (or required buffer size) DWORD pcReturned=0; // pointer to number of PORT_INFO_* structures stored into buffer if (!EnumPorts(NULL,2,port,0,&pcbNeeded,&pcReturned)) { //TRACE("1\r\n"); //根据手册可知, //pcbNeeded 说明:If cbBuf is equal to or greater than this value, //the variable pointed to by pcbNeeded represents the number of bytes stored into the buffer //所以经过此步后可以得知系统需要分配的内存缓存的大小,大小为pcbNeeded } port = new BYTE[pcbNeeded]; if (EnumPorts(pName,Level,port,pcbNeeded,&pcbNeeded,&pcReturned)) { //TRACE("2\r\n"); //经过此步骤,我们可以得到所需的打印机信息结构的数组指针是port //返回端口的个数是pcReturned //返回信息的字节大小是pcbNeeded } PORT_INFO_2 *pPort; pPort = (PORT_INFO_2*)port; //指针类型转换后可直接使用里的信息。这个是个人理解 int i; for(i=0;i<pcReturned;i++) { TRACE("%s\r\n",pPort->pPortName); //返回设备名称 pPort ++; }