This depends on your type of application. If you are going to create a GUI application or need to perform other tasks, you must use a worker thread or overlapped I/O.
Your current implementation uses a blocking write call. This means that the call will not return until all data has been send or a timeout occurs. During this time your application can not perform other tasks like processing user input.
For a simple console test program you can just put the write calls into a while loop that breaks upon errors or key press (include
conio.h and use
_kbit()
followed by a
_getch()
call when a key was pressed).
I suggest to use the above simple method at least until the communication is working.
[EDIT: Added example]
int GetPressedKey()
{
int ret = 0;
if (_kbhit())
{
ret = _getch();
}
return ret;
}
while (1)
{
if (!WriteFile(hSerial, bytes_to_send, 5, &bytes_written, NULL))
break;
fprintf(stderr, "%d bytes written\n", bytes_written);
if (GetPressedKey())
break;
if (GetPressedKey())
break;
}
CloseHandle(hSerial);