Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

COM port open/close/status 2

Status
Not open for further replies.

scottmanjoe

Technical User
Mar 28, 2003
15
IN
How to:
1.Open a COM port.
2.Close a COM port.
3.Check whether COM port is already in use.

I think we will use a CreateFile().
Thanks,
Scott
 
Example:
Open:
****
HANDLE hComm = CreateFile("COM2:",
GENERIC_READ , // GENERIC_WRITE
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,//FILE_FLAG_OVERLAPPED,//if OVERLAPPED Read
NULL);

if (hComm== INVALID_HANDLE_VALUE){
// Failed to get a handle for scanner comm

}
return (hComm);

Close:
******
CloseHandle(hComm );

Checks:
*******
DCB dcb;
COMMTIMEOUTS ctmo=
{
50,
MAXWORD,
MAXWORD,
0,
0
};

if (!SetCommTimeouts( hComm,&ctmo))
{
// Cannot set the commtimeouts structure
}
else
{
// Call BuildCommDCB()
or
FillMemory(&dcb, sizeof(dcb), 0);
GetCommState(hComm,&dcb))
}

-obislavu-
 
Hi obislavu,
Thanks for the reply.
Suppose we have opened the COM port using one thread and we want to close it using some other thread and there is no way that the second thread knows about the handle.
Is it possible to retrieve the handle later on and then use CloseHandle.
Thanks,
Scott
 
Handles are process-scope, not thread-scope. So you can store the handle in a global variable or some other object accessible from both threads, and that way pass the handle from the first to the second thread.

You could also pass the handle from one thread to the other by posting a message, if the second thread is running a message pump or queue.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top