Configuring a Communications Resource

The following example opens a handle to COM1 and fills in a DCB structure with the current configuration. The DCB structure is then modified and used to reconfigure the device.

DCB dcb;
HANDLE hCom;
DWORD dwError;
BOOL fSuccess;

hCom = CreateFile( "COM1",
    GENERIC_READ | GENERIC_WRITE,
    0,    // comm devices must be opened w/exclusive-access 
    NULL, // no security attributes 
    OPEN_EXISTING, // comm devices must use OPEN_EXISTING 
    0,    // not overlapped I/O 
    NULL  // hTemplate must be NULL for comm devices 
    );

if (hCom == INVALID_HANDLE_VALUE) 
{
    dwError = GetLastError();

    // handle error 
}

// Omit the call to SetupComm to use the default queue sizes.
// Get the current configuration.

fSuccess = GetCommState(hCom, &dcb);

if (!fSuccess) 
{
    // Handle the error. 
}

// Fill in the DCB: baud=9600, 8 data bits, no parity, 1 stop bit. 

dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;

fSuccess = SetCommState(hCom, &dcb);

if (!fSuccess) 
{
    // Handle the error. 
}