473,756 Members | 3,655 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

WriteFile says open comm port has invalid handle?

Howdy,

I'm trying to write data out the com port. I have taken the code from the
sample on the MSDN Library CD and used the parts that seem relevant. I can
open the com port with CreateFile and get a valid file handle back. But
when I try to write to it, the WriteFile comes back and tells me the handle
is invalid. The program has control of the port because using Hyperterminal,
I can't connect when the program is connected.

There must be something simple I'm missing but I can't see it.

Any ideas???

--
Frank Perry
LavaLeaf Software
Nov 17 '05 #1
3 5280
On Fri, 1 Apr 2005 08:51:04 -0800, "Frank Perry"
<Fr********@dis cussions.micros oft.com> wrote:
Howdy,

I'm trying to write data out the com port. I have taken the code from the
sample on the MSDN Library CD and used the parts that seem relevant. I can
open the com port with CreateFile and get a valid file handle back. But
when I try to write to it, the WriteFile comes back and tells me the handle
is invalid. The program has control of the port because using Hyperterminal,
I can't connect when the program is connected.

There must be something simple I'm missing but I can't see it.


Whittle your routine down to the smallest compilable code that
reproduces the error and let us see it.

--
Sev
Nov 17 '05 #2
Howdy,

Here is the code. It is a connect function that calls a config function, a
send function where the problem shows up, and a close function.

The connect produces a valid handle but the send always says the handle is
invalid. It may be that there is more to it than that but that is the only
message I get. The com port is com6. I have the sample code from MSDN and
that is the source of the original code. It works but it is in old style
windows with message maps etc. and I don't want to use that for the app.

Here is the code:

bool CComm485::CommO penConnection()
{

HANDLE hCommWatchThrea d ;
DWORD dwThreadID ;
COMMTIMEOUTS CommTimeOuts ;
char szPort[30];
int iRetVal;

wsprintf( szPort, "%s%d", "COM", m_iCommPort ) ;

// open COMM device

m_hCommHandle =
CreateFile( szPort,
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // no security attrs
OPEN_EXISTING,
FILE_ATTRIBUTE_ NORMAL |
FILE_FLAG_OVERL APPED, // overlapped I/O
NULL );
if(m_hCommHandl e ==INVALID_HANDL E_VALUE)
return ( FALSE ) ;
else
{
// get any early notifications

SetCommMask( m_hCommHandle, EV_RXCHAR ) ;

// setup device buffers
DWORD dwError;
if(!SetupComm( m_hCommHandle, 4096, 4096 ) )
dwError = GetLastError();

// purge any information in the buffer

PurgeComm( m_hCommHandle, PURGE_TXABORT | PURGE_RXABORT |
PURGE_TXCLEAR | PURGE_RXCLEAR ) ;

// set up for overlapped I/O

CommTimeOuts.Re adIntervalTimeo ut = 0xFFFFFFFF ;
CommTimeOuts.Re adTotalTimeoutM ultiplier = 0 ;
CommTimeOuts.Re adTotalTimeoutC onstant = 1000 ;
// CBR_9600 is approximately 1byte/ms. For our purposes, allow
// double the expected time per character for a fudge factor.
CommTimeOuts.Wr iteTotalTimeout Multiplier = 2*CBR_9600/9600 ;
CommTimeOuts.Wr iteTotalTimeout Constant = 0 ;
SetCommTimeouts ( m_hCommHandle, &CommTimeOut s ) ;
}

iRetVal = SetUpConnection () ;

if (!iRetVal)
{
m_bConnected = TRUE ;

// Create a secondary thread
// to watch for an event.

/* if ( NULL == (hCommWatchThre ad =
CreateThread( (LPSECURITY_ATT RIBUTES) NULL,
0,
(LPTHREAD_START _ROUTINE) CommWatchProc,
(LPVOID) this,
0, &dwThreadID )))
{
m_bConnected = FALSE ;
CloseHandle( m_hCommHandle ) ;
iRetVal = -1 ;
}
else
*/ {
m_dwThreadID = dwThreadID ;
m_hTermWnd = (HWND) hCommWatchThrea d ;

// assert DTR

EscapeCommFunct ion( m_hCommHandle, SETDTR ) ;

}
}
else
{
m_bConnected = FALSE ;
CloseHandle( m_hCommHandle ) ;
}

// restore cursor
// test it here
// char* szBuffer;
// szBuffer = (char*) malloc(100);
// memset(szBuffer , 'X', 100);
// WriteCommBlock( npTTYInfo, szBuffer, 100);
// free(szBuffer);

m_bConnected = true;
return m_bConnected ; //(bool) OpenConnection( pInfo);
}

bool CComm485::CommC loseConnection( )
{
m_bConnected = false;

// disable event notification and wait for thread
// to halt

SetCommMask( m_hCommHandle, 0 ) ;

// block until thread has been halted

while(m_dwThrea dID != 0);

// kill the focus

// KillTTYFocus( hWnd ) ;

// drop DTR

EscapeCommFunct ion( m_hCommHandle, CLRDTR ) ;

// purge any outstanding reads/writes and close device handle

PurgeComm( m_hCommHandle, PURGE_TXABORT | PURGE_RXABORT |
PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
CloseHandle( m_hCommHandle ) ;
//return (bool) CloseConnection ((NPTTYINFO) m_pTTYInfo);
return true;
}

int CComm485::SendR esponse(LPSTR szResponse, int iLength)
{
NPTTYINFO pInfo = (NPTTYINFO) m_pTTYInfo;

DWORD dwBytesWritten;

// WriteCommBlock( pInfo, szResponse , iLength);
int fWriteStat = WriteFile( m_hCommHandle, szResponse, iLength,
&dwBytesWritten , &m_osWrite ) ;

if (!fWriteStat)
{
DWORD dwLastError = GetLastError();
char szErrMsg[100];
FormatMessage(F ORMAT_MESSAGE_F ROM_SYSTEM,NULL ,dwLastError,NU LL,szErrMsg,
100,NULL);
dwLastError = 0;
}
return 0;
}

int CComm485::SetUp Connection()
{
BOOL fRetVal ;
DCB dcb ;
;

dcb.DCBlength = sizeof( DCB ) ;

if(!GetCommStat e( m_hCommHandle, &dcb ) )
{
DWORD dwLastError = GetLastError();
char szErrMsg[100];
FormatMessage(F ORMAT_MESSAGE_F ROM_SYSTEM,NULL ,dwLastError,NU LL,szErrMsg,
100,NULL);
dwLastError = 0;
}

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

// setup hardware flow control

dcb.fDtrControl = DTR_CONTROL_DIS ABLE ;
dcb.fRtsControl = RTS_CONTROL_DIS ABLE ;
dcb.fOutxCtsFlo w = FALSE;
dcb.fOutxDsrFlo w = FALSE;
dcb.fDtrControl = FALSE;
dcb.fDsrSensiti vity = FALSE;
dcb.fRtsControl = FALSE;

// setup software flow control
// bSet = 0; // no flow control
dcb.fInX = dcb.fOutX = FALSE ;
// dcb.XonChar = ASCII_XON ;
// dcb.XoffChar = ASCII_XOFF ;
// dcb.XonLim = 100 ;
// dcb.XoffLim = 100 ;

// other various settings
dcb.fAbortOnErr or = FALSE;

dcb.fBinary = TRUE ;
dcb.fParity = TRUE ;

fRetVal = SetCommState( m_hCommHandle, &dcb ) ;
DWORD dwError;
if(!fRetVal)
{
dwError = GetLastError();
char szErrMsg[100];
FormatMessage(F ORMAT_MESSAGE_F ROM_SYSTEM,NULL ,dwError,NULL,s zErrMsg,
100,NULL);
dwError = 0;
return -1;
}

return 0;

}

Any help would be appreciated.

Frank Perry

"Severian" wrote:
On Fri, 1 Apr 2005 08:51:04 -0800, "Frank Perry"
<Fr********@dis cussions.micros oft.com> wrote:
Howdy,

I'm trying to write data out the com port. I have taken the code from the
sample on the MSDN Library CD and used the parts that seem relevant. I can
open the com port with CreateFile and get a valid file handle back. But
when I try to write to it, the WriteFile comes back and tells me the handle
is invalid. The program has control of the port because using Hyperterminal,
I can't connect when the program is connected.

There must be something simple I'm missing but I can't see it.


Whittle your routine down to the smallest compilable code that
reproduces the error and let us see it.

--
Sev

Nov 17 '05 #3
On Fri, 1 Apr 2005 10:05:05 -0800, "Frank Perry"
<Fr********@dis cussions.micros oft.com> wrote:
"Severian" wrote:
On Fri, 1 Apr 2005 08:51:04 -0800, "Frank Perry"
<Fr********@dis cussions.micros oft.com> wrote:
>Howdy,
>
>I'm trying to write data out the com port. I have taken the code from the
>sample on the MSDN Library CD and used the parts that seem relevant. I can
>open the com port with CreateFile and get a valid file handle back. But
>when I try to write to it, the WriteFile comes back and tells me the handle
>is invalid. The program has control of the port because using Hyperterminal,
>I can't connect when the program is connected.
>
>There must be something simple I'm missing but I can't see it.


Whittle your routine down to the smallest compilable code that
reproduces the error and let us see it.


Howdy,

Here is the code. It is a connect function that calls a config function, a
send function where the problem shows up, and a close function.

The connect produces a valid handle but the send always says the handle is
invalid. It may be that there is more to it than that but that is the only
message I get. The com port is com6. I have the sample code from MSDN and
that is the source of the original code. It works but it is in old style
windows with message maps etc. and I don't want to use that for the app.

Here is the code:


<snip>

That was not enough to compile and test, so all I can do is guess.

1) Have you checked in the debugger that the m_hCommHandle is the same
when you call WriteFile? (Not corrupted or changed by something.)

2) Is m_osWrite properly intialized, including the event handle?

--
Phillip Crews aka Severian
Micrisoft MVP, Windows SDK
Posting email address is real
Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
8700
by: dim | last post by:
Copied directly from exaple book but not working.... All i get is an empty 0 byte file Call to GetLastError directly after the call to WriteFile returns 0 (NO_ERROR) but no data sees to be written :-( ?????????? Thx
1
16710
by: Chuck Rittersdorf | last post by:
Hi There I am having a problem using the win32 API from VB6. I am trying to send a command string to a printer(zebra TLP 2742) on LPT1 using the folowing API functions CreateFile and WriteFile I have written C code which works fine, just the VB translation/port
0
1692
by: Nitin Narang | last post by:
I have a piece of code which is moved to .NET VC7 recently from VC6 and there has been an apparent change in behavior using CreateFile/Writefile functionality. I am creating a file on a shared drive using the win32 Api and using the handle returned, i call writefile giving number of bytes to write as 1MB. Shared directory on the machine maps to F: drive ( "shared" is the directory name maps to " F:") In VC6 on executing...
1
3641
by: sarath1111 | last post by:
hi all, I am using comm port for serial communication between 2 PC's using C language. Once I have initialized the COMM port, Is there any option of closing the port in C language. Thanks in Advance, Sarath.B
1
4458
by: Paul | last post by:
Hi, I am extending an existing MFC app to use Unicode (for a Japanese version of the interface elements). The app's purpose is to control a peripheral device through the serial port, and the device only understands ansi strings (in fact, I synthesize a character stream and send it as though it was typed into a terminal). The problem seems to be that the VC++ 6 linker insists that if I use the #define UNICODE and _UNICODE preprocessor...
7
2765
by: Michael Chong | last post by:
I wrote a program that communicate with SerialComm. In every 300 milliseconds, my program continuously send & receive data via the serial port once the program starts. My program is once in a while, the serial port seems corrupted because when my data is sent, it doesn't go through the serial port, so as same to receive process. In order to fix this, I have to close the port and reopen the port again. Why?!! Is there any way to fix...
0
1064
by: Michael Chong | last post by:
I am not very good in C++ problem and this is my codes below. I do not know whether I got handshaking involve in my code. Could you guys let me know? HANDLE OpenComm(char *lpszPort, int nBaud, char *nParity, int nData, int nStop) { HANDLE hCom; LPDCB lpDcb;
4
2635
by: Iceman.Aragorn | last post by:
I'm having an odd problem where im reading input from a comm port (the maker of the software that exports the data TO the comm port is unhelpful). What im reading is fixed length (13 character) sets of data seperated by CR/linefeed. At first, it simply seemed like i was getting messed up data, due to encoding it wrong, or using the wrong font, or something like that, but it turns out, when i analyze the byte stream, that the data i get...
2
1912
by: Hank | last post by:
Hello, I would like to get some opinions on using the Comm Port with Access 2000. We have a few jobs coming in that require us to interface with a PLC via the Comm Port. My partner feels we should use a Visual Basic Front End and the VB component as opposed to Access. Has anyone had good luck interfacing to a Comm Port using Access?
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10034
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9872
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9843
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7248
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5142
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.