vbnet串口程序 vb串口编程实例( 四 )


使用LPOVERLAPPED结构,WriteFile()立即返回,不必等待写操作完成,实现非阻塞 通信.此时, WriteFile()返回FALSE, GetLastError()返回ERROR_IO_PENDING.
int err=GetLastError();
if (!fWriteStat) {
if(GetLastError() == ERROR_IO_PENDING){
while(!GetOverlappedResult(hCom, WRITE_OS( npTTYInfo ),
dwBytesWritten, TRUE )) {
dwError = GetLastError();
if(dwError == ERROR_IO_INCOMPLETE){// normal result if not finished
dwBytesSent += dwBytesWritten; continue; }
......................
//我使用了多线程技术 , 在辅助线程中监视串口,有数据到达时依靠事件驱动,读入数据并向主线程报告(发送数据在主线程中,相对说来,下行命令的数据总是少得多);并且,WaitCommEvent()、ReadFile()、WriteFile()都使用了非阻塞通信技术,依靠重叠(overlapped)读写操作 , 让串口读写操作在后台运行 。
vb.net 怎么用事件触发的方式读取串口数据首先vbnet串口程序:
textbox里没有显示vbnet串口程序,是因为SerialPort1和TextBox2不是同一线程创建vbnet串口程序的vbnet串口程序,需要跨线程操作 。需要用到委托,这样才能显示出来 。
其次:
我觉得用串口的接收数据事件更好一些 。
下面代码供参考:
'----------------------
'串口接收数据事件,其实比用定时器更好,
'触发事件的条件可以自己在form_load中设置ReceivedBytesThreshold属性数值 , 默认为ReceivedBytesThreshold=1
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim strRecvData As String = ""
strRecvData = https://www.04ip.com/post/SerialPort1.ReadExisting
Call disPlayComData(strRecvData)
End Sub
Delegate Sub callback(ByVal strT As String) '定义委托
Sub showString(ByVal comdata As String) '显示结果
Me.TextBox1.Text = "结果:"comdata
End Sub
Sub disPlayComData(ByVal strTmp As String) '判定是否为跨线程
If Me.TextBox1.InvokeRequired Then
Dim d As New callback(AddressOf showString)
Me.Invoke(d, New Object() {strTmp})
Else
Me.TextBox1.Text = strTmp
End If
End Sub
关于vbnet串口程序和vb串口编程实例的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

推荐阅读