Read COM (serial) port using CreateFile? 
Author Message
 Read COM (serial) port using CreateFile?

I am trying to read a bytestream coming in from a serial port.  Heard that
in VB6 you could use something like "Open "LPT1" For Input As #1", but I
searched the web and saw that for .Net I would have to call the CreateFile()
Win32 API.  (Short using MSComm OCX, but that's in Visual Studio 6 and I
would like to avoid that.)

I am able to get a handle back from the CreateFile Win32 API call but I get
an overflow error when I use it to initialize a System.inPtr object.  I'm
stumped because the documentation shows that the constructor is overloaded
to take either an integer or a long.

I am using VB.Net Trial Edition 7.09492, .Net Framework 1.0.3705 if that
makes a difference.  (OS right now is Windows XP home edition.)   I just
installed VB.Net the first time a couple of hours ago--being that this is my
first VB.Net application, and I've never tried serial comms before, there is
a very good chance that I'm probably just doing something dumb.

Any ideas?  Here's the code:

Sub Main()
    Dim handle As Integer = CreateFile("COM1", GENERIC_READ, 0, 0,
    If handle <> -1 Then
        Dim h As New System.IntPtr(handle) 'GETTING OVERFLOW ERROR HERE
        Dim myStream As New System.IO.FileStream(h,
System.IO.FileAccess.ReadWrite, True)

        ' do stuff with the port
        Dim v As Integer = myStream.ReadByte()
    End If
End Sub

Private Declare Function CreateFile Lib "kernel32" _
    Alias "CreateFileA" ( _
    ByVal lpFileName As String, _
    ByVal dwDesiredAccess As Long, _
    ByVal dwShareMode As Long, _
    ByVal lpSecurityAttributes As Long, _
    ByVal dwCreationDisposition As Long, _
    ByVal dwFlagsAndAttributes As Long, _
    ByVal hTemplateFile As Long) As Long

    ' Note: lpSecurityAttributes is really SECURITY_ATTRIBUTES ptr

    Private Const GENERIC_READ As Integer = &H80000000
    Private Const OPEN_EXISTING As Integer = 3

Fri, 04 Feb 2005 09:26:15 GMT  
 Read COM (serial) port using CreateFile?
Have a look here


Corrado Cavalli

Fri, 04 Feb 2005 15:35:34 GMT  
 [ 2 post ] 

 Relevant Pages 

1. CreateFile,ReadFile,WriteFile using COM ports and API

2. using the serial port (COM) in a VB Script

3. How do I read my serial port using Access VBA

4. read data from serial port using vba for Access

5. Createfile API problem with COM ports

6. Createfile to Open a Com port or Disk Drive

7. Createfile to Open a Com port or Disk Drive

8. How to loop comm port control to read text files through serial port in VB3

9. Using serial port without using MSCOMM

10. Problem with Serial Port COM (RS232)

11. How to access the serial com port

12. com and serial port control


Powered by phpBB® Forum Software