使用委托方式處理:
創新互聯建站專業為企業提供新羅網站建設、新羅做網站、新羅網站設計、新羅網站制作等企業網站建設、網頁設計與制作、新羅企業網站模板建站服務,十余年新羅做網站經驗,不只是建網站,更提供有價值的思路和整體網絡服務。
Public?Class?Form1
Dim?mSTR?As?String
Dim?strData?As?String
Dim?strDat?As?String
Dim?mRecvByte()?As?Byte
Dim?Hexsj?As?String
Dim?form2?As?Form
Private?Sub?SerialPort1_DataReceived(ByVal?sender?As?Object,?ByVal?e?As?System.IO.Ports.SerialDataReceivedEventArgs)?Handles?SerialPort1.DataReceived
Dim?mSize?As?Integer?=?Me.SerialPort1.BytesToRead
ReDim?mRecvByte(mSize?-?1)
SerialPort1.Read(mRecvByte,?0,?mSize)
BeginInvoke(New?EventHandler(AddressOf?ONMLoadA),?SerialPort1.BytesToRead())?'使用委托方式顯示接收到的字符串
End?Sub
Sub?ONMLoadA(ByVal?sender?As?System.Object,?ByVal?e?As?System.EventArgs)?'委托
strDat?=?""
TextBox1.Text?=?""
Dim?i?As?Integer
For?i?=?0?To?UBound(mRecvByte)?'mSize?-?1
strData?=?strData??IIf(mRecvByte(i)??15,?Hex(mRecvByte(i)),?"0"??Hex(mRecvByte(i)))??"?"
Next
Dim?sj?As?Byte
For?i?=?1?To?Len(strData)?Step?3?'處理為ASCII字符
sj?=?Val("H"??Mid(strData,?i,?2))
If?sj??32?Or?sj??128?Then?'當接收字節中有Chr(0)時,其后字符被切割
strDat?=?strDat??"."
Else
strDat?=?strDat??Chr(sj)
End?If
Next
TextBox1.Text?=?strDat?'顯示字符
TextBox2.Text?=?strData?'顯示為16進制
TextBox3.Text?=?Len(strData)?/?3
End?Sub
vb.net的話
For
Each
sp
As
String
In
My.Computer.Ports.SerialPortNames
cbxport.Items.Add(sp)
Next
vb6.0的話要調用API查看串口相關信息存在的注冊表。
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM
通過讀注冊表的方法獲得串口數量,當然也可以獲得串口號了。
Option
Explicit
Private
Declare
Function
RegOpenKey
Lib
"advapi32.dll
"
Alias
"RegOpenKeyA
"
(ByVal
hKey
As
Long,
ByVal
lpSubKey
As
String,
phkResult
As
Long)
As
Long
Private
Declare
Function
RegQueryInfoKey
Lib
"advapi32.dll
"
Alias
"RegQueryInfoKeyA
"
(ByVal
hKey
As
Long,
ByVal
lpClass
As
String,
lpcbClass
As
Long,
ByVal
lpReserved
As
Long,
lpcSubKeys
As
Long,
lpcbMaxSubKeyLen
As
Long,
lpcbMaxClassLen
As
Long,
lpcValues
As
Long,
lpcbMaxValueNameLen
As
Long,
lpcbMaxValueLen
As
Long,
lpcbSecurityDescriptor
As
Long,
lpftLastWriteTime
As
Long)
As
Long
Private
Const
HKEY_LOCAL_MACHINE
=
H80000002
'
獲得當前系統的
COM
口的數量
Function
GetCOMCount()
As
Integer
Dim
ret
As
Long,
cntCOM
As
Long
RegOpenKey
HKEY_LOCAL_MACHINE,
"HARDWARE\DEVICEMAP\SERIALCOMM
",
ret
RegQueryInfoKey
ret,
"
",
0,
0,
0,
0,
0,
cntCOM,
0,
0,
0,
GetCOMCount
=
cntCOM
End
Function
Private
Sub
Command1_Click()
MsgBox
"您的機器有
"
GetCOMCount
"
個串口。
",
vbOKOnly,
"串口數量
"
End
Sub
不是很明白你的題意
strHex = strHex + [String].Format("{0:X2} "
這里的意思是把每個字節數據轉換成了十六進制,每個字節占兩個字符
如果你串口收到的4個字節數據:43,27,56,200
那么你的結果是:2B1B38C8
即receivebytes.Text="2B1B38C8"
不足兩位的補0
如果你串口收到的4個字節數據:3,27,56,200
那么你的結果是:031B38C8
即receivebytes.Text="031B38C8"
文章名稱:vb.net串口源碼 vb串口編程
URL地址:http://vcdvsql.cn/article34/hephpe.html
成都網站建設公司_創新互聯,為您提供軟件開發、營銷型網站建設、電子商務、外貿網站建設、建站公司、網站營銷
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯