Tecnología

Inicio

Cómo acceder a los puertos serie y paralelo mediante Visual Basic 6

Si está desarrollando un programa utilizando Visual Basic 6, y quiere ser capaz de acceder a los puertos serie y paralelo, debe insertar códigos de programación Visual Basic específicos en el archivo ".vb" del programa. Puede editar este archivo directamente en el entorno de programación Visual Basic, pero el código para añadir el acceso a los puertos serie y paralelo es muy larga y específica.

Instrucciones

1 Haga doble clic en el icono del programa "Microsoft Visual Studio .NET" para iniciar el programa. Haga clic en el menú "Archivo", mueva el cursor del ratón sobre la opción "Nuevo" y seleccionar la opción "Proyecto".

2 Haga clic en la opción "Proyectos de Visual Basic" bajo el título "Tipos de proyecto". Haga clic en la opción "Aplicación de consola" bajo el título "plantillas".

3 Escriba un nombre para la aplicación en el espacio correspondiente y haga clic en el botón "OK" para crear el proyecto. El archivo "Module1.vb" se abre automáticamente.

4 Pegue el siguiente código en el archivo "Module1.vb" del proyecto antes de la línea de código que lee "Módulo Module 1":

Option Strict On

'Definir una clase CommException que hereda de la clase ApplicationException,
'Y luego tirar un objeto de tipo CommException cuando recibe un mensaje de error.
clase CommException
ApplicationException hereda
Sub (Razón ByVal como secuencia) Nuevo

MyBase.New(Reason)

End Sub
End Class

5 Pegue el siguiente código en el archivo "Module1.vb" del proyecto después de la línea de código que lee "Módulo Module 1":

'Declarar estructuras.
Estructura pública DCB
Como DCBlength pública Int32
Como BaudRate pública Int32
fBitFields públicas Como Int32 'Ver comentarios en WIN32API.TXT
Como wReserved pública Int16
Como XonLim pública Int16
Como XoffLim pública Int16
ByteSize pública As Byte
Paridad pública As Byte
StopBits públicas As Byte
XonChar pública As Byte
XoffChar pública As Byte
ErrorChar pública As Byte
EofChar pública As Byte
EvtChar pública As Byte
Como wReserved1 pública Int16 'reservados; No utilice
Estructura End

COMMTIMEOUTS estructura pública
Como ReadIntervalTimeout pública Int32
Como ReadTotalTimeoutMultiplier pública Int32
Como ReadTotalTimeoutConstant pública Int32
Como WriteTotalTimeoutMultiplier pública Int32
Como WriteTotalTimeoutConstant pública Int32
Estructura End

'Declarar constantes.
Public Const GENERIC_READ Como Int32 = & H80000000
Public Const GENERIC_WRITE Como Int32 = & H40000000
Public Const OPEN_EXISTING Como Int32 = 3
Public Const FILE_ATTRIBUTE_NORMAL Como Int32 = & H80
Public Const NOPARITY Como Int32 = 0
Public Const ONESTOPBIT Como Int32 = 0

'Declarar referencias a las funciones externas.
Public Declare Auto función CreateFile Lib "kernel32.dll"


(ByVal lpFileName como secuencia, de ByVal dwDesiredAccess Como Int32,

ByVal dwShareMode As Int32, ByVal lpSecurityAttributes As IntPtr, _
ByVal dwCreationDisposition As Int32, ByVal dwFlagsAndAttributes As Int32, _
ByVal hTemplateFile As IntPtr) As IntPtr

Public Declare Auto Función GetCommState Lib "kernel32.dll" (ByVal ncid como IntPtr, _
ByRef lpDCB Como DCB) As Boolean

Public Declare Auto Función SetCommState Lib "kernel32.dll" (ByVal ncid como IntPtr, _
ByRef lpDCB Como DCB) As Boolean

Public Declare GetCommTimeouts función Auto Lib "kernel32.dll" (ByVal hFile como IntPtr, _
ByRef lpCommTimeouts Como COMMTIMEOUTS) As Boolean

Declarar Auto Función Pública SetCommTimeouts Lib "kernel32.dll" (ByVal hFile como IntPtr, _
ByRef lpCommTimeouts Como COMMTIMEOUTS) As Boolean

Public Declare Auto Función de escritura de archivo Lib "kernel32.dll" (ByVal hFile como IntPtr,
ByVal lpBuffer As Byte (), ByVal nNumberOfBytesToWrite Como Int32,

ByRef lpNumberOfBytesWritten As Int32, ByVal lpOverlapped As IntPtr) As Boolean

Public Declare Auto función ReadFile Lib "kernel32.dll" (ByVal hFile como IntPtr,
ByVal lpBuffer As Byte (), ByVal nNumberOfBytesToRead Como Int32,

ByRef lpNumberOfBytesRead As Int32, ByVal lpOverlapped As IntPtr) As Boolean

Public Declare Auto Función CloseHandle Lib "kernel32.dll" (ByVal hObject como IntPtr) As Boolean

6 Pegue el siguiente código en el archivo "Module1.vb" del proyecto después de la línea de código que lee "Sub Main":

'Declarar las variables locales que va a utilizar en el código.
Dim hSerialPort, hParallelPort como IntPtr
El éxito Dim As Boolean
Dim MyDCB Como DCB
MyCommTimeouts dévil como COMMTIMEOUTS
Dim BytesWritten, BytesRead Como Int32
Dim Buffer () As Byte

'Declarar las variables a utilizar para la codificación.
Dim oEncoder Como Nueva System.Text.ASCIIEncoding
Dim oEnc Como System.Text.Encoding = oEncoder.GetEncoding (1252)

'Convertir la cadena de bytes ().
Buffer = oEnc.GetBytes ( "Test")

Try
' Access the serial port.
Console.WriteLine("Accessing the COM1 serial port")
' Obtain a handle to the COM1 serial port.
hSerialPort = CreateFile("COM1", GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, _
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)
' Verify that the obtained handle is valid.
If hSerialPort.ToInt32 = -1 Then
Throw New CommException("Unable to obtain a handle to the COM1 port")
End If
' Retrieve the current control settings.
Success = GetCommState(hSerialPort, MyDCB)
If Success = False Then
Throw New CommException("Unable to retrieve the current control settings")
End If
' Modify the properties of the retrieved DCB structure as appropriate.
' WARNING: Make sure to modify the properties according to their supported values.
MyDCB.BaudRate = 9600
MyDCB.ByteSize = 8
MyDCB.Parity = NOPARITY
MyDCB.StopBits = ONESTOPBIT
' Reconfigure COM1 based on the properties of the modified DCB structure.
Success = SetCommState(hSerialPort, MyDCB)
If Success = False Then
Throw New CommException("Unable to reconfigure COM1")
End If
' Retrieve the current time-out settings.
Success = GetCommTimeouts(hSerialPort, MyCommTimeouts)
If Success = False Then
Throw New CommException("Unable to retrieve current time-out settings")
End If
' Modify the properties of the retrieved COMMTIMEOUTS structure as appropriate.
' WARNING: Make sure to modify the properties according to their supported values.
MyCommTimeouts.ReadIntervalTimeout = 0
MyCommTimeouts.ReadTotalTimeoutConstant = 0
MyCommTimeouts.ReadTotalTimeoutMultiplier = 0
MyCommTimeouts.WriteTotalTimeoutConstant = 0
MyCommTimeouts.WriteTotalTimeoutMultiplier = 0
' Reconfigure the time-out settings, based on the properties of the modified COMMTIMEOUTS structure.
Success = SetCommTimeouts(hSerialPort, MyCommTimeouts)
If Success = False Then
Throw New CommException("Unable to reconfigure the time-out settings")
End If
' Write data to COM1.
Console.WriteLine("Writing the following data to COM1: Test")
Success = WriteFile(hSerialPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero)
If Success = False Then
Throw New CommException("Unable to write to COM1")
End If
' Read data from COM1.
Success = ReadFile(hSerialPort, Buffer, BytesWritten, BytesRead, IntPtr.Zero)
If Success = False Then
Throw New CommException("Unable to read from COM1")
End If
Catch ex As Exception
Console.WriteLine(Ex.Message)
Finally
' Release the handle to COM1.
Success = CloseHandle(hSerialPort)
If Success = False Then
Console.WriteLine("Unable to release handle to COM1")
End If
End Try

7 Pegar el código siguiente inmediatamente después del código que se inserta en el archivo "Module1.vb" en el Paso 6:

Tratar

' Parallel port.
Console.WriteLine("Accessing the LPT1 parallel port")
' Obtain a handle to the LPT1 parallel port.
hParallelPort = CreateFile("LPT1", GENERIC_READ Or GENERIC_WRITE, 0, IntPtr.Zero, _
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero)
' Verify that the obtained handle is valid.
If hParallelPort.ToInt32 = -1 Then
Throw New CommException("Unable to obtain a handle to the LPT1 port")
End If
' Retrieve the current control settings.
Success = GetCommState(hParallelPort, MyDCB)
If Success = False Then
Throw New CommException("Unable to retrieve the current control settings")
End If
' Modify the properties of the retrieved DCB structure as appropriate.
' WARNING: Make sure to modify the properties according to their supported values.
MyDCB.BaudRate = 9600
MyDCB.ByteSize = 8
MyDCB.Parity = NOPARITY
MyDCB.StopBits = ONESTOPBIT
' Reconfigure LPT1 based on the properties of the modified DCB structure.
Success = SetCommState(hParallelPort, MyDCB)
If Success = False Then
Throw New CommException("Unable to reconfigure LPT1")
End If
' Retrieve the current time-out settings.
Success = GetCommTimeouts(hParallelPort, MyCommTimeouts)
If Success = False Then
Throw New CommException("Unable to retrieve current time-out settings")
End If
' Modify the properties of the retrieved COMMTIMEOUTS structure as appropriate.
' WARNING: Make sure to modify the properties according to their supported values.
MyCommTimeouts.ReadIntervalTimeout = 0
MyCommTimeouts.ReadTotalTimeoutConstant = 0
MyCommTimeouts.ReadTotalTimeoutMultiplier = 0
MyCommTimeouts.WriteTotalTimeoutConstant = 0
MyCommTimeouts.WriteTotalTimeoutMultiplier = 0
' Reconfigure the time-out settings, based on the properties of the modified COMMTIMEOUTS structure.
Success = SetCommTimeouts(hParallelPort, MyCommTimeouts)
If Success = False Then
Throw New CommException("Unable to reconfigure the time-out settings")
End If
' Write data to LPT1.
' Note: You cannot read data from a parallel port by calling the ReadFile function.
Console.WriteLine("Writing the following data to LPT1: Test")
Success = WriteFile(hParallelPort, Buffer, Buffer.Length, BytesWritten, IntPtr.Zero)
If Success = False Then
Throw New CommException("Unable to write to LPT1")
End If
Catch ex As Exception
Console.WriteLine(Ex.Message)
Finally
' Release the handle to LPT1.
Success = CloseHandle(hParallelPort)
If Success = False Then
Console.WriteLine("Unable to release handle to LPT1")
End If
End Try

Console.WriteLine (& quot; Presione ENTRAR para salir de & quot;)
Console.ReadLine ()

8 Haga clic en el menú "Build" y seleccionar la opción "Generar solución". Haga clic en el menú "Test" y seleccionar la opción "Inicio". La aplicación ahora tiene acceso a los puertos serie y paralelo.