How to use the Win32 API to communicate with a COM port (RS232)

I am trying to use the win32 API to communicate with a COM port; I found this http://www.robbayer.com/files/serial-win.pdf

hSerial = CreateFile("COM1",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);

I am using VS2008 and it complains error C2664: 'CreateFileW': it is not possible to convert parameter 1 from 'const char [5]' to 'LPCWSTR'

OK, I think that it is not necessary that "COM1" be a char * type,

I tried pouring it LPCWSTR ("COM1"), then it compiles without problems.

However, it returns "ERROR opening serial port -1", so it does not find the com port successfully. I think direct casting is not the right way?

Please tell me what I have to do to make this work.

msdn http://msdn.microsoft.com/en-us/library/ms810467.aspx

, "gszPort"

+3
2

_T("COM1") LPCWSTR("COM1"). . , , _T - .

, Windows API (, -1), ( GetLastError FormatMessage), .

+3

Unicode CreateFile CreateFileW, "" . , L, :

CreateFile(L"COM1", ...);

:

CreateFileW(L"COM1", ...);

"ANSI", Unicode:

CreateFileA("COM1", ...);

Unicode ANSI-, , L. : TEXT(x) _T(x). , Windows API <tchar.h>, - C. Windows API, TEXT.

CreateFile(TEXT("COM"), ...);

, , ANSI. Windows, , Unicode , , ANSI, . L, .

+3

All Articles