1.环境 Windows7 vs2010
2.语言 c++
3.设备 钱箱与打印机的LPT1口相连
4.控制指令 27 112 7(十进制)
5.代码
-
CString sPort;
-
//sPort.Format(_T("\\\\.\\LPT1"));//两种方法都行
-
sPort.Format(_T("LPT1"));
-
#if 1
-
//设置为重叠 异步IO
-
HANDLE hPort = CreateFile(sPort,GENERIC_READ | GENERIC_WRITE,0,NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);//创建文件
-
if (hPort == INVALID_HANDLE_VALUE || hPort == (HANDLE)ERROR_INVALID_HANDLE)
-
{
-
CString lsreturn = L"open fail";
-
ExecutePrint(rect,LogFont,pDC,lsreturn.GetBuffer(0),lsreturn.GetLength(),DT_CENTER | DT_BOTTOM | DT_SINGLELINE);
-
return false;
-
}
-
char lco[4];
-
-
lco[0] = 27;
-
lco[1] = 112;
-
lco[2] = 7;
-
lco[3] = '\0';
-
-
DWORD writebyte = 0;
-
DWORD writecount = 4;
-
-
OVERLAPPED* pOverlapped = new OVERLAPPED;
-
ZeroMemory(pOverlapped, sizeof(OVERLAPPED));
-
pOverlapped->Offset = 0;
-
pOverlapped->OffsetHigh = 0;
-
pOverlapped->hEvent = 0;
-
//pOverlapped->hEvent = (HANDLE) this;
-
int lret = 0;
-
lret = WriteFile(hPort,lco,writecount,&writebyte,pOverlapped);//向文件中直接写命令
-
if (lret == 0)
-
{
-
int err = GetLastError();
-
if (GetLastError() == ERROR_IO_PENDING)//重叠IO进行中
-
{
-
GetOverlappedResult(hPort,pOverlapped,&writebyte,true);
-
}
-
else//其他的错误
-
{
-
delete pOverlapped;
-
CloseHandle(hPort);
-
CString lsreturn = L"Failed to write";
-
ExecutePrint(rect,LogFont,pDC,lsreturn.GetBuffer(0),lsreturn.GetLength(),DT_CENTER | DT_BOTTOM | DT_SINGLELINE);
-
return false;
-
}
-
}
-
#endif
-
-
#if 0
-
//同步IO 2种方法都可以
-
HANDLE hPort = CreateFile(sPort,GENERIC_READ | GENERIC_WRITE,0,NULL, OPEN_EXISTING, 0, NULL);
-
if (hPort == INVALID_HANDLE_VALUE || hPort == (HANDLE)ERROR_INVALID_HANDLE)
-
{
-
CString lsreturn = L"open fail";
-
ExecutePrint(rect,LogFont,pDC,lsreturn.GetBuffer(0),lsreturn.GetLength(),DT_CENTER | DT_BOTTOM | DT_SINGLELINE);
-
return false;
-
}
-
char lco[4];
-
lco[0] = 27;
-
lco[1] = 112;
-
lco[2] = 7;
-
lco[3] = '\0';
-
-
DWORD writebyte = 0;
-
DWORD writecount = 4;
-
int lret = 0;
-
lret = WriteFile(hPort,lco,writecount,&writebyte,NULL);
-
if (lret == 0)
-
{
-
int err = GetLastError();
-
CloseHandle(hPort);
-
CString lsreturn = L"Failed to write";
-
ExecutePrint(rect,LogFont,pDC,lsreturn.GetBuffer(0),lsreturn.GetLength(),DT_CENTER | DT_BOTTOM | DT_SINGLELINE);
-
return false;
-
}
-
#endif
-
CloseHandle(hPort);
打开LPT1文件
向文件中写入命令
关闭文件
另外,在网上还查到一些别的指令,如 27 112 0 60 225(十进制的)。但是中间的那个0会被看成空字符,指令会被截断,不知道用什么方法解决。
阅读(1644) | 评论(0) | 转发(0) |