分享好友 编程语言首页 频道列表

一个基于API的VB.net串口通讯类 vbnet串口通信如何编写

VisualBasic  2023-02-12 15:210
VB.net的串口通讯支持总是让人觉得有所不足,在使用VB6的MsComm32.ocx时,很多人都会在VB.net的开发中觉得很困扰。
  
  这里讲述的VB.net串口通讯类使用native代码,并且它是通API调用实现的,你会发现VB.net的串口通讯就是这么简单。
  
  在说明如何使用这个类前,需要说明的是,本类只是一个VB.net的串口通讯演示,你可能需要根据你的情况修改后使用。另外,本类的目的是通过例子教会你在无需ocx控件和第三方组件的支持下用VB.net开发串口通讯程序,所有并没有完善的异常错误处理。
  
  1.初始化并打开串口
  
  创建一个CRs232类的实例,并在调用Open方法前设置好串口通讯参数。
  
  例:
  
  Dim moRS232 as New Rs232()
  
  With moRs232
  
  .Port = 1                          '// Uses COM1
  
  .BaudRate = 2400                   '// 波特率 2400
  
  .DataBit = 8                        '// 8 data bits
  
  .StopBit = Rs232.DataStopBit.StopBit_1      '// 停止位 1
  
  .Parity = Rs232.DataParity.Parity_None      '// 无奇偶校验
  
  .Timeout = 500                      '//超时时间500 ms
  
  End With
  
  
  '// 初始化并打开串口
  
  moRS232.Open ()
  
  '// 串口打开后,你可以随意地控制DTR/RTS
  
  moRS232.Dtr = True
  
  moRS232.Rts = True
  
  为了处理异常情况,建议你使用Try...Catch。
  
  2.发送数据
  
  本类为Rx和Tx准备了两个缓冲区(buffer),发送数据时,只需要设置TxData属性为你需要发送的数据,然后调用Tx方法就可以了。
  
  例如:
  
  moRS232.TxData = txtTx.Text
  
  moRS232.Tx()
  
  3.接收数据
  
  先调用Rx方法(参数为您需要从串口读取的字节数),然后读取RxData属性。
  
  例如:
  
  moRS232.Rx(10)            '// 从串口通讯缓冲区里读取10字节
  
  Dim sRead as String=moRs232.RxData
  
  需要注意的是,当本类无法用串口读取到所需的字节数,程序线程在超时异常发生前是锁死的,超时时间通过Timout属性设置。
  
  如果你没有指明需要读取的字节数,本类默认使用512字节来读取缓冲区里的数据。
  
  
一个基于API的VB.net串口通讯类

  版本信息:
  
  Project History
  1st Public release Beta2 (10/08/2001)
  
  Rev.1 (28.02.2002)
  1. Added ResetDev, SetBreak and ClearBreak to the EscapeCommFunction constants
  2. Added the overloaded Open routine.
  3. Added the modem status routines, properties and enum.
  4. If a read times out, it now returns a EndOfStreamException (instead of a simple Exception).
  5.Compiled with VS.Net final
  
  Rev.2 (01.03.2002)
  Added Async support
  
  Rev.3 (07.04.2002)
  Minor bugs fixed
  
  Rev.3a (05/05/2002)
  Fixed BuildCommmDCB problem
  
  Rev.4 (24/05/2002)
  Fixed problem with ASCII Encoding truncating 8th bit
  
  Rev.5 (27/05/2002)
  Added IDisposable / Finalize implementation
  
  Rev.6 (14/03/2003)
  Fixed problem on DCB fields Initialization
  
  Rev.7 (26/03/2003)
  Added XON/XOFF support
  
  Rev.8 (12/07/2003)
  Added support to COM port number greater than 4
  
  Rev.9 (16/07/2003)
  Added CommEvent to detect incoming chars/events(!)
  Updated both Tx/Rx method from Non-Ovelapped to Overlapped mode
  Removed unused Async methods and other stuff.
  
  Rev.10 (21/07/2003)
  Fixed incorrect character handling when using EnableEvents()
  
  Rev.11 (12/08/2003)
  Fixed some bugs reported by users
  
  Rev.12 (01/09/2003)
  Removed AutoReset of internal buffers and added PurgeBuffer() method
  
  Rev.13 (02/09/2003)
  Update internal stuff now using Win32Exception instead of GetLastError+FormatMessage APIs
  
  Rev.14 (14/09/2003)
  Added IsPortAvailable() function (thanks to Tom Lafleur for the hint)
  Revised some API declaration
  Fixed some problems with Win98/Me OS (thanks to Alex Komissarov for the feedback)
  
  Rev.15 (24/09/2003)
  Fixed bug introduced on rev.14 (sorry for that...)
  
  Rev.16 (16/10/2003)
  Added SetBreak/ClearBreak methods for sending break signal over the line.
  
  Rev.17 (02/11/2003)
  Fixed incorrect field on COMMCONFIG Structure.
  
  Rev.18 (03/03/2004)
  Fixed bug causing troubles accessing already in use ports (folks, thanks for the feedback!)
  
  Rev.19 (08/04/2004)
  Fixed bug on DTR property (thanks to Charles-Olivier Théroux)
  
  Rev.20 (12/07/2004)
  CommEvent is no more raised on a secondary thread (please note that this is valid only if event handler is not associated with a static method)
  pEventsWatcher now uses a background thread
  
  Rev.21 (24/10/2004)
  Fixed EscapeCommFunction declaration
  Fixed incorrect Pariti enum entry
  
  Rev.22 (05/03/2005)
  Fixed memory leak causing random program termination without any message.
  Thanks to Ralf Gedrat for testing this scenario.
  
  Rev.23 (05/04/2005)
  Fixed bug DisableEvents not working bug (Thanks to Jean Bédard)

查看更多关于【VisualBasic】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
Windows API Reference for C#, VB.NET
不错的.net 下用API的参考站点地址在:http://www.webtropy.com/articles/Win32-API-DllImport-art9.asp 下面摘抄分类,便于大家直接就拿来用: File, Memory, Process, Threading, Time, Console, and Comm control(kernel32.dll) _hread_hwrite_lclose_lcr

0评论2023-03-16877

[VB][ASP.NET]FileUpload控件「批次上传 / 多档案同时上传」的范例
FileUpload控件「批次上传 / 多档案同时上传」的范例 (VB语法) http://www.dotblogs.com.tw/mis2000lab/archive/2008/05/14/3986.aspx    FileUpload控件真的简单好用,不使用它来作批次上传,却要改用别的方法,实在不聪明。要用就一次用到底,公开File

0评论2023-02-10976

第八章 VB中ActiveX控件的使用
轉自:http://wwww.hyit.edu.cn/edu/vb/study/index.htm第八章          VB中ActiveX控件的使用8.1  概述     这里的ActiveX控件是指VB标准工具箱里没有的控件,用时需从“工程”菜单里选择“部件…”(或右键单击工具箱,从快捷菜单中选择“部

0评论2023-02-10615

第二章 VB的界面设计
轉自:http://wwww.hyit.edu.cn/edu/vb/study/index.htm第二章         VB的界面设计2.1  VB用户界面设计基础1. 概述   界面的设计有两步:先绘制控件,然后确定控件属性。   绘制控件:在工具箱里单击想画的控件,在窗体里按下鼠标并拖曳,然后

0评论2023-02-10497

VB6多线程,关键段操作 vb6.0 多线程
Option Explicit Declare Function GetLastError Lib "kernel32" () As Long 'Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long 'Declare Sub ExitThread Lib "kernel32" (Optional ByVal dwExitCode

0评论2023-02-09486

VB.NET调用IE,并且等待
            Dim p As New Process            '获得URL            aURL = GetURL()            '获得IE路径            p.StartInfo.FileName = System.Environment.GetFolderPath( _ 

0评论2023-02-09939

vb的VSFlexGrid控件 vb msflexgrid
多行选中VSFlexGrid的SelectionMode = flexSelectionListBox,现在可以配合Ctrl进行多行选择循环取值用vsflexgrid.SelectedRows 可以得到你选择的行的总数量然后用循环可以得到具体的行中具体列的内容Dim Temp  As StringDim i As IntegerFor i =

0评论2023-02-09868

转载-公历转换农历VB示例 公历转农历函数
Option ExplicitPrivate LunarInfo(1 To 150) As Double '从1900-2049年这150年的农历信息码Private SolarMonth(1 To 12) As Integer '阳历12个月的天数Private Gan(1 To 10) As String '农历的天干Private Zhi(1 To 12) As String '农历的地支Private Animal

0评论2023-02-09982

[转] VB的Ping 模块
图:Ping通的情况图:Ping失败的情况下面是源代码(VB6):(完善的出错控制,所以是个好函数)Option ExplicitPrivate Const IP_SUCCESS As Long = 0Private Const IP_STATUS_BASE As Long = 11000Private Const IP_BUF_TOO_SMALL As Long = (11000 + 1)Private

0评论2023-02-09407

VB.NET withevent 自定义事件处理
Module Module1    Private WithEvents aemp As part2    Sub Main()        Dim chen As New part2("chen lili", 20000)        aemp = chen        Console.WriteLine(chen.Name" prevouis salary is "chen.Salary)      

0评论2023-02-09571

VB6操作ACCESS文件 vb+access
VB6操作ACCESS文件Option ExplicitConst Dict_DB = "adatabase.mdb"'先要引用Microsoft ActiveX Data Objects 2.8 LibraryPublic cnn As ADODB.ConnectionPublic rst As ADODB.Recordset, rst2 As ADODB.RecordsetPublic cmd As ADODB.CommandPrivate Sub For

0评论2023-02-09762

VB用API实现各种对话框(总结) vbs简单代码对话框
VB用API实现各种对话框(总结)  各种对话框(总结)标准对话框(SmDialog)Option Explicit''定义一个全局变量,用于保存字体的各种属性Public Type SmFontAttrFontName As String '字体名FontSize As Integer '字体大小FontBod As Boolean '是否黑体FontItalic A

0评论2023-02-09401

VB中的正则表达式 vb 正则表达式
RegExp对象提供简单的正则表达式支持功能。  RegExp对象的用法:Function RegExpTest(patrn, strng)Dim regEx, Match, Matches ' 建立变量。Set regEx = New RegExp ' 建立正则表达式。regEx.Pattern = patrn ' 设置模式。regEx.IgnoreCase = True ' 设置是

0评论2023-02-09890

VB 调用水晶报表2
Set rptApp = New CRPEAuto.ApplicationrptApp.LogOnServer "PDSODBC.DLL", "sbd", "sbd", "epm", "epmis"Set rpt = rptApp.OpenReport(App.Path"\\计划管理\\月度保养计划.rpt")rpt.SQLQueryString = strSQL \'strS

0评论2023-02-09631

【VB】StrConv函数 vbUnicode用法
【VB】StrConv函数StrConv(string, conversion, LCID)vbUnicode64根据系统的缺省码页将字符串转成Unicode。vbFromUnicode128将字符串由 Unicode 转成系统的缺省码页。    Windows系统对字符采用了DBCS编码,它是一套单字节和双字节的混合编码,即西文与AS

0评论2023-02-09999

vb.net 时间类型转字符串后的格式
做下记录vb.net中时间类型转换成字符串也是可以设置格式的,如:  DateTime.Now.ToString("yyyyMMdd hh:mm:ss") ----print:   20090313 15:12:30  DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")---Print:    2009-03-13 15:12:05等等,其余还可以设置

0评论2023-02-09354

更多推荐