\\Form1.Designer.cs
using System.Runtime.InteropServices;//引入dll文件中的函数
namespace WindowsApplication20130113
{
partial class Form1 { [DllImport("CommApi.dll")] private static extern bool SetSerialCom(Int32 nPort, Int32 lBaudRate, Int32 DataBit, Int32 lParity, Int32 lStopbit); [DllImport("CommApi.dll")] private static extern Int32 ReadCom(byte[] TheFirstAddrofInputBuff, Int32 lSizeofByte, Int32 msWaitTime); [DllImport("CommApi.dll")] private static extern bool WriteCom(byte[] TheFirstAddrofInputBuff, Int32 lSizeofByte); [DllImport("CommApi.dll")] private static extern int CloseSerialPort(); \\其他代码 }
}
然后便可以在源代码中引用SetSerialCom等函数。
vb.net
'命名空间 Imports System.Runtime.InteropServices Public Class Form1 Inherits Form Private Declare Function SetSerialCom Lib "commapi" (ByVal nPort As Int32, ByVal BaudRate As Int32, ByVal DataBit As Int32, ByVal Parity As Int32, ByVal Stopbit As Int32) As Boolean Private Declare Function ReadCom Lib "commapi" (ByRef TheFirstAddrofInputBuff As Byte, ByVal SizeofByte As Int32, ByVal msWaitTime As Int32) As Int32 Private Declare Function WriteCom Lib "commapi" (ByRef TheFirstAddrofOutputBuff As Byte, ByVal SizeofByte As Int32) As Boolean Private Declare Sub CloseSerialPort Lib "commapi" ()
注意:vb.net中的ByRef:传地址 (因为vb.net数组一般是用首地址传递),ByVal:传值;