Come accedere porte seriali e parallele utilizzando Visual Basic 6

September 13

Se si sta sviluppando un programma che utilizza Visual Basic 6, e si vuole essere in grado di accedere alle porte seriali e parallele, è necessario inserire specifici codici di programmazione Visual Basic in file ".VB" del programma. È possibile modificare questo file direttamente in ambiente di programmazione Visual Basic, ma il codice per aggiungere l'accesso alle porte seriali e parallele è molto lunga e specifica.

istruzione

1 Fare doppio clic sull'icona del programma "Microsoft Visual Studio .NET" per avviare il programma. Fare clic sul menu "File", spostare il cursore del mouse sopra l'opzione "Nuovo" e selezionare l'opzione "Progetto".

2 Selezionare l'opzione "Progetti di Visual Basic" sotto la voce "Tipi progetto". Selezionare l'opzione "Applicazione console" sotto il titolo "Modelli".

3 Digitare un nome per l'applicazione nell'apposito spazio e cliccare sul pulsante "OK" per creare il progetto. Il file "Module1.vb" si apre automaticamente.

4 Incollare il seguente codice nel file del progetto "Module1.vb" prima della riga di codice che legge "Module Module1":

Option Strict On

'Definire una classe CommException che eredita dalla classe ApplicationException,
'E poi gettare un oggetto di tipo CommException quando si riceve un messaggio di errore.
Classe CommException
ApplicationException eredita
Sub (Motivo ByVal come stringa) Nuovo

MyBase.New(Reason)

End Sub
End Class

5 Incollare il seguente codice nel file del progetto "Module1.vb" dopo la riga di codice che legge "Module Module1":

'Declare strutture.
Struttura pubblica DCB
Public DCBlength Come Int32
Public BaudRate Come Int32
fBitFields pubblici Come Int32 'vedere i commenti a Win32api.txt
Public wReserved Come Int16
Public XonLim Come Int16
Public XoffLim Come Int16
ByteSize pubblico As Byte
Parità pubblico As Byte
StopBits pubblico come Byte
XonChar pubblico As Byte
XoffChar pubblico As Byte
ErrorChar pubblico As Byte
EofChar pubblico As Byte
EvtChar pubblico As Byte
wReserved1 Public Come Int16 'riservati; Non usare
fine Structure

COMMTIMEOUTS struttura pubblica
Public ReadIntervalTimeout Come Int32
Public ReadTotalTimeoutMultiplier Come Int32
Public ReadTotalTimeoutConstant Come Int32
WriteTotalTimeoutMultiplier Public Come Int32
WriteTotalTimeoutConstant Public Come Int32
fine Structure

'Declare costanti.
Public Const GENERIC_READ Come Int32 = & H80000000
Public Const GENERIC_WRITE Come Int32 = & H40000000
Public Const OPEN_EXISTING Come Int32 = 3
Public Const FILE_ATTRIBUTE_NORMAL Come Int32 = & H80
Public Const NOPARITY Come Int32 = 0
Public Const ONESTOPBIT Come Int32 = 0

'Dichiarare riferimenti a funzioni esterne.
Public Declare Auto Function CreateFile Lib "kernel32.dll"


(ByVal lpFileName As String, ByVal dwDesiredAccess Come 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 Function GetCommState Lib "kernel32.dll" (ByVal ncid come IntPtr, _
ByRef lpDCB come DCB) come booleano

Public Declare Auto Function SetCommState Lib "kernel32.dll" (ByVal ncid come IntPtr, _
ByRef lpDCB come DCB) come booleano

Public Declare GetCommTimeouts funzione Auto Lib "kernel32.dll" (ByVal hFile come IntPtr, _
ByRef lpCommTimeouts As COMMTIMEOUTS) come booleano

Public Declare Auto Function SetCommTimeouts Lib "kernel32.dll" (ByVal hFile come IntPtr, _
ByRef lpCommTimeouts As COMMTIMEOUTS) come booleano

Public Declare Auto Function WriteFile Lib "kernel32.dll" (ByVal hFile come IntPtr,
ByVal lpBuffer As Byte (), ByVal nNumberOfBytesToWrite Come Int32,

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

Public Declare Auto Function ReadFile Lib "kernel32.dll" (ByVal hFile come IntPtr,
ByVal lpBuffer As Byte (), ByVal nNumberOfBytesToRead Come Int32,

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

Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject come IntPtr) come booleano

6 Incollare il seguente codice nel file del progetto "Module1.vb" dopo la riga di codice che legge "Sub Main":

'Dichiarare le variabili locali che verranno utilizzate nel codice.
Dim hSerialPort, hParallelPort come IntPtr
Successo fioco come booleano
Dim MyDCB Come DCB
MyCommTimeouts fiochi come COMMTIMEOUTS
Dim bytesWritten, BytesRead Come Int32
Dim Buffer () As Byte

'Dichiarare le variabili da utilizzare per la codifica.
Dim oEncoder come nuovo System.Text.ASCIIEncoding
Dim oEnc Come System.Text.Encoding = oEncoder.GetEncoding (1252)

'Conversione di stringhe in Byte ().
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 Incollare il codice seguente immediatamente dopo il codice è stato inserito nel file "Module1.vb" al punto 6:

Provare

' 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; premere INVIO per chiudere & quot;)
Console.ReadLine ()

8 Fare clic sul menu "Build" e selezionare l'opzione "Genera soluzione". Fare clic sul menu "Debug" e selezionare l'opzione "Start". L'applicazione ha ora accesso alle porte seriali e parallele.