一、MSCOMM32
步骤:
1.下载MSCOMM32组件(在哪下我也忘了);
2.注册组件,新建一个*.reg文件,将以下代码复制,粘贴
REGEDIT
HKEY_CLASSES_ROOT/Licenses = Licensing: Copying the keys may be a violation of established copyrights.
HKEY_CLASSES_ROOT/Licenses/4250E830-6AC2-11cf-8ADB-00AA00C00905 = kjljvjjjoquqmjjjvpqqkqmqykypoqjquoun
3.将MSCOMM32组件添加到VS2003.NET工具箱里,这时你可以看见一个电话的图标就是它了;
4.运行*.reg文件;
5.从工具箱里拖一个控件到窗体上,配置它的属性或者在代码里设置 如下:
private void InitComPort()
{
try
{
axMSComm1.CommPort=3;//我这里用的是com3
if(axMSComm1.PortOpen)
axMSComm1.PortOpen = false;
axMSComm1.RThreshold = 1; //每接收一个字符则激发OnComm()事件
axMSComm1.Settings = "38400,n,8,1";
axMSComm1.DTREnable = true;
axMSComm1.Handshaking = MSCommLib.HandshakeConstants.comNone;
//axMSComm1.InputMode = MSCommLib.InputModeConstants.comInputModeText; //文本
axMSComm1.InputMode = MSCommLib.InputModeConstants.comInputModeBinary; //二进制
axMSComm1.InputLen = 0; //清除接收缓冲区
axMSComm1.NullDiscard = false;
axMSComm1.OnComm +=new EventHandler(axMSComm1_OnComm); //注册一个OnComm事件
axMSComm1.PortOpen = true; //打开串口
this.msg.Text = "设备已成功启动!";
}
catch
{
this.msg.Text = "设备启动失败!";
}
}
6.发送数据:
private void SendData()
{
try
{
//二进制
byte[] byOut = new byte[2];
byOut[0] = 0x01;
byOut[1] = 0x02;
axMSComm1.Output = byOut; //向缓冲区写入数据
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
7.接收数据
/// <summary>
/// 每接收一个字符则激发OnComm()事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void axMSComm1_OnComm(object sender, System.EventArgs e)
{
axMSComm1.InputMode = MSCommLib.InputModeConstants.comInputModeBinary; //二进制
axMSComm1.InputLen = 0;
byte[] indata = (byte[])axMSComm1.Input;//接收数据
}