星期日, 7月 11, 2004

Using COM Port API with VB

COM1 => OPEN_EXISTING

http://www.yesky.com/SoftChannel/72342371928637440/20040417/1788826_1.shtml

long hfile= CreateFile("c:\\test.txt", GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_
WRITE,NULL, OPEN_EXISTING,FILE_ELAG_OVERLAPPED,NULL)

OPEN"COM1:2400,N,8,1,BIN"FOR RANDOM AS #1

http://support.microsoft.com/default.aspx?scid=kb;en-us;823179&Product=vb6

API define:

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

Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As
Long) _
As Long

Private Declare Function WriteFile Lib "kernel32" (ByVal hFile As Long,ByVal lpBuffer As String, ByVal nNumberOfBytesToWrite As Long, lpNumberOfBytesWritten As Long, lpOverlapped As Any) As Long

' CreateFile dwDesiredAccess Konstanten
Private Const GENERIC_READ = &H80000000 ' Nur Lesen
Private Const GENERIC_WRITE = &H40000000 ' Nur Schreiben

' CreateFile dwShareMode Konstanten
Private Const FILE_SHARE_READ = &H1
Private Const FILE_SHARE_WRITE = &H2

' CreateFile dwCreationDisposition Konstanten
' ===========================================
' Erstellt eine neue Datei und uberschreibt eine bereits vorhandene
Private Const CREATE_ALWAYS = 2
' Erstellt eine neue Datei nur, wenn sie noch nicht existiert
Private Const CREATE_NEW = 1
' Offnet eine bereits vorhande Datei bzw. erstellt diese,
' wenn sie noch nicht existiert
Private Const OPEN_ALWAYS = 4
' Offnet eine bereits vorhandene Datei
Private Const OPEN_EXISTING = 3
' Offnet eine bereits vorhandene Datei und loscht den Inhalt
Private Const TRUNCATE_EXISTING = 5


Private Sub Command1_Click()

'On Error Resume Next
'Open "COM1:9600,N,8,1" For Output As #1
'If Err > 0 Then
' MsgBox "Oen error"
'Else
' Print #1, "atz"
' Print #1, "atz"
' Print #1, "atz"
' Print #1, "atz"
' Close #1
'End If

Dim hCOM As Long
Dim r As Long
Dim COM_Cmd As String
Dim slen As Long

COM_Cmd = "atz" & vbCrLf

hCOM = CreateFile("COM1", GENERIC_WRITE, 0, 0&, OPEN_EXISTING, 0, 0)
r = WriteFile(hCOM, COM_Cmd, LenB(COM_Cmd), slen, ByVal 0&)
r = CloseHandle(hCOM)

End Sub
張貼留言