AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > VB编程

MsComm 文字传输

51自学网 http://www.wanshiok.com
假如您对 MSComm 的基本属性还不了解, 建议请先至MSComm 基本介绍一文中详读

表单画面

' 表单部分
'-------------------------------------------------------------
Form.Name = "Form1"
Caption = "Form1"
CommandButton.Name = Command2
Caption = "停止测试"
CommandButton.Name = Command1
Caption = "开始测试"
TextBox.Name = Text1
MSComm.Name = MSComm1
DTREnable = -1'True
Label.Name = Label1
AutoSize = -1'True
Caption = "欲送出的资料 - 按下[Enter]送出"
Label.Name = Label3
BorderStyle = 1'单线固定
Label.Name = Label2
AutoSize = -1'True
Caption = "折返显示"

' 程式部分
'-------------------------------------------------------------
Option Explicit
' 设一个此表单的区域变数,来作终止读取通讯埠的指标
Dim bStop As Boolean
' 设一个区域变数,来作读取通讯埠的暂存区
Dim InString As String

Private Sub Command1_Click()
bStop = False
Text1.SetFocus
With MSComm1
' 设定通讯埠号,可依照您的需求更改
.CommPort = 2
' 设定传输速率等,可依照您的需求更改
.Settings = "14400,N,8,1"
' 将通讯埠打开
.PortOpen = True
End With
' 假如使用者未按下「停止测试」钮(bStop = False), 则继续读取
Do While Not bStop
If MSComm1.InBufferCount Then
' 通讯埠中假如有资料的话, 则读取进来
InString = InString & MSComm1.Input
' 如果资料中有 Chr(13) 和 Chr(10) 的话, 则显示出来
If InStr(InString, vbCrLf) Then
Label3.Caption = Label3.Caption & InString
InString = ""
' 暂时把系统资源让出来给其它的程式使用
DoEvents
End If
End If
DoEvents
Loop
End Sub

Private Sub Command2_Click()
' 按下「停止测试」钮时, 把 bStop 设为「真」(True)
' 如此程式才会停止等待(或读取)通讯埠所收到的资料
bStop = True
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
bStop = True
' 把通讯埠关闭, 才不会影响其它程式的使用通讯埠
MSComm1.PortOpen = False
End
End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)
' 当按下 [Enter] 时, 把 Text1 文字框中的资料送至通讯埠
If KeyAscii = 13 Then
MSComm1.Output = Text1.Text & vbCrLf
Text1.Text = ""
KeyAscii = 0
End If
End Sub

 

 

 
上一篇:SMTP协议简介(Simple Mail Transfer Protocol)  下一篇:Modem通讯意外处理