#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
HANDLE hPort = CreateFile("COM2",
GENERIC_WRITE|GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
DCB dcb;
bool writebyte(char*data)
{
DWORD byteswritten;
if (!GetCommState(hPort,&dcb))
{
printf("\nSerial port can't be open\n");
return false;
}
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if (!SetCommState(hPort,&dcb))
return false;
bool retVal = WriteFile(hPort,data,1,&byteswritten,NULL);
return retVal;
}
int ReadByte()
{
int Val;
BYTE Byte;
DWORD dwBytesTransferred;
DWORD dwCommModemStatus;
if (!GetCommState(hPort,&dcb))
return 0;
SetCommMask(hPort,EV_RXCHAR | EV_ERR);
WaitCommEvent (hPort,&dwCommModemStatus,0);
if (dwCommModemStatus & EV_RXCHAR)
ReadFile (hPort,&Byte,1,&dwBytesTransferred,0);
Val = Byte;
return Val;
}
int main() {
POINT p;
int x;
int y;
int z;
while(0==0){
GetCursorPos(&p);
x = p.x;
y = p.y;
HDC hDC;
hDC = GetDC(NULL);
cin >> z;
cout << GetPixel(hDC, x, y) << endl;
Sleep(z);
ReleaseDC(NULL, hDC);
char data = GetPixel(hDC, x, y);
if (writebyte(&data))
cout <<" DATA SENT.. " << (int)data<< "\n";
}
}
在通过串行通讯发送数据的部分,而不是将数据作为GetPixel(hDC,x,y)发送,它只发送值“-1”。我认为这是因为字符只适用于小整数,而我给出的输出是非常长的数字。我试图将它改为long int,但我仍然得到相同的结果。它只发送“-1”。我认为解决方案可能会在发送数据之前将char转换为long int或long int char,但我不知道如何......有人可以帮助我吗?如何将long int转换为char
GetPixel返回一个COLORREF,不要假装它是一个字符。当你尝试发送一个大整数作为单个字节时,你期望发生什么? – john 2013-04-24 15:19:46
由于COLORREF是4个字节,所以您需要调用writebyte 4次才能发送它。 – vipw 2013-04-24 15:22:22
@wipw可能更喜欢重写writebyte,以便它可以发送多个字节 – john 2013-04-24 15:23:56