#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