C#窗体应用程序调用C++动态链接库(dll)

最近完成了一个项目,项目难度不大,但是过程中还是遇到了一些问题,特此记录下来,以备不时之需。该项目实现了MCU控制一些LED灯的状态,这个很简单无需多讲,MCU是通过串口通讯接收上位机APP的指令,然后再去根据指令执行控制LED的动作的。上位机APP是通过C#写的,其实C#有自带的串口控件,最简单的方式是直接利用这个控件来实现通讯,但是为了方便客户的开发,我还是决定做成一个可以调用的动态链接库(DLL)来实现,后期用户只需要参考我们的APP调用这个DLL就可以了。下面将讲解如何完成DLL和APP的编写,以及过程中遇到的一些问题。

1.动态链接库(dll):

1.1 创建新项目

这里我使用的是VS2019,界面跟之前的版本有所不同:

 

 

        

        

 

这样,一个工程就建好了,接下来编写代码。

  1.2 代码编辑:

 

     1.2.1 创建好的项目中自带一个dllmain.cpp文件,这个文件一般情况下不需要更改。

     1.2.2 需要创建其他源文件或者头文件,可以右击“解决方案资源管理器”这一栏中的“源文件”或“头文件”,选择“添加”,选择“新建项”。在本次项目中增加了4个文件,“WzSerialPort.h”,“WzSerialPort.cpp”,“SBC7835_DLL.cpp”,“SBC7835_DLL.h”,其中“WzSerialPort.h”和“WzSerialPort.cpp”是实现串口通讯功能的源文件和头文件,“SBC7835_DLL.cpp”,“SBC7835_DLL.h”是应用层的代码,是自定义的数据格式以及串口的开启及关闭:

WzSerialPort.cpp:

#include "pch.h"
#include "WzSerialPort.h"

#include <stdio.h>
#include <string.h>

#include <WinSock2.h>
#include <windows.h>

WzSerialPort::WzSerialPort()
{

}

WzSerialPort::~WzSerialPort()
{

}

bool WzSerialPort::open(const char* portname,
	int baudrate,
	char parity,
	char databit,
	char stopbit,
	char synchronizeflag)
{
	this->synchronizeflag = synchronizeflag;
	HANDLE hCom = NULL;
	if (this->synchronizeflag)
	{
		//同步方式
		hCom = CreateFileA(portname, //串口名
			GENERIC_READ | GENERIC_WRITE, //支持读写
			0, //独占方式,串口不支持共享
			NULL,//安全属性指针,默认值为NULL
			OPEN_EXISTING, //打开现有的串口文件
			0, //0:同步方式,FILE_FLAG_OVERLAPPED:异步方式
			NULL);//用于复制文件句柄,默认值为NULL,对串口而言该参数必须置为NULL
	}
	else
	{
		//异步方式
		hCom = CreateFileA(portname, //串口名
			GENERIC_READ | GENERIC_WRITE, //支持读写
			0, //独占方式,串口不支持共享
			NULL,//安全属性指针,默认值为NULL
			OPEN_EXISTING, //打开现有的串口文件
			FILE_FLAG_OVERLAPPED, //0:同步方式,FILE_FLAG_OVERLAPPED:异步方式
			NULL);//用于复制文件句柄,默认值为NULL,对串口而言该参数必须置为NULL
	}

	if (hCom == (HANDLE)-1)
	{
		return false;
	}

	//配置缓冲区大小 
	if (!SetupComm(hCom, 1024, 1024))
	{
		return false;
	}

	// 配置参数 
	DCB p;
	memset(&p, 0, sizeof(p));
	p.DCBlength = sizeof(p);
	p.BaudRate = baudrate; // 波特率
	p.ByteSize = databit; // 数据位

	switch (parity) //校验位
	{
	case 0:
		p.Parity = NOPARITY; //无校验
		break;
	case 1:
		p.Parity = ODDPARITY; //奇校验
		break;
	case 2:
		p.Parity = EVENPARITY; //偶校验
		break;
	case 3:
		p.Parity = MARKPARITY; //标记校验
		break;
	}

	switch (stopbit) //停止位
	{
	case 1:
		p.StopBits = ONESTOPBIT; //1位停止位
		break;
	case 2:
		p.StopBits = TWOSTOPBITS; //2位停止位
		break;
	case 3:
		p.StopBits = ONE5STOPBITS; //1.5位停止位
		break;
	}

	if (!SetCommState(hCom, &p))
	{
		// 设置参数失败
		return false;
	}

	//超时处理,单位:毫秒
	//总超时=时间系数×读或写的字符数+时间常量
	COMMTIMEOUTS TimeOuts;
	TimeOuts.ReadIntervalTimeout = 1000; //读间隔超时,该时间为串口每次接收等待的时间间隔,数据不多可以把该时间改小,这里每次等待1000mS间隔
	TimeOuts.ReadTotalTimeoutMultiplier = 500; //读时间系数
	TimeOuts.ReadTotalTimeoutConstant = 5000; //读时间常量
	TimeOuts.WriteTotalTimeoutMultiplier = 500; // 写时间系数
	TimeOuts.WriteTotalTimeoutConstant = 2000; //写时间常量
	SetCommTimeouts(hCom, &TimeOuts);

	PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR);//清空串口缓冲区

	memcpy(pHandle, &hCom, sizeof(hCom));// 保存句柄

	return true;
}

void WzSerialPort::close()
{
	HANDLE hCom = *(HANDLE*)pHandle;
	CloseHandle(hCom);
}

int WzSerialPort::send(const void* buf, int len)
{
	HANDLE hCom = *(HANDLE*)pHandle;

	if (this->synchronizeflag)
	{
		// 同步方式
		DWORD dwBytesWrite = len; //成功写入的数据字节数
		BOOL bWriteStat = WriteFile(hCom, //串口句柄
			buf, //数据首地址
			dwBytesWrite, //要发送的数据字节数
			&dwBytesWrite, //DWORD*,用来接收返回成功发送的数据字节数
			NULL); //NULL为同步发送,OVERLAPPED*为异步发送
		if (!bWriteStat)
		{
			return 0;
		}
		return dwBytesWrite;
	}
	else
	{
		//异步方式
		DWORD dwBytesWrite = len; //成功写入的数据字节数
		DWORD dwErrorFlags; //错误标志
		COMSTAT comStat; //通讯状态
		OVERLAPPED m_osWrite; //异步输入输出结构体

							  //创建一个用于OVERLAPPED的事件处理,不会真正用到,但系统要求这么做
		memset(&m_osWrite, 0, sizeof(m_osWrite));
		m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, L"WriteEvent");

		ClearCommError(hCom, &dwErrorFlags, &comStat); //清除通讯错误,获得设备当前状态
		BOOL bWriteStat = WriteFile(hCom, //串口句柄
			buf, //数据首地址
			dwBytesWrite, //要发送的数据字节数
			&dwBytesWrite, //DWORD*,用来接收返回成功发送的数据字节数
			&m_osWrite); //NULL为同步发送,OVERLAPPED*为异步发送
		if (!bWriteStat)
		{
			if (GetLastError() == ERROR_IO_PENDING) //如果串口正在写入
			{
				WaitForSingleObject(m_osWrite.hEvent, 1000); //等待写入事件1秒钟
			}
			else
			{
				ClearCommError(hCom, &dwErrorFlags, &comStat); //清除通讯错误
				CloseHandle(m_osWrite.hEvent); //关闭并释放hEvent内存
				return 0;
			}
		}
		return dwBytesWrite;
	}
}

int WzSerialPort::receive(void* buf, int maxlen)
{
	HANDLE hCom = *(HANDLE*)pHandle;

	//if (this->synchronizeflag)
	//{
	//    //同步方式,这里因为发送用了同步,接收想用异步,又没有重新初始化串口打开,就直接注释掉用串口异步接收了
	//    DWORD wCount = maxlen; //成功读取的数据字节数
	//    BOOL bReadStat = ReadFile(hCom, //串口句柄
	//        buf, //数据首地址
	//        wCount, //要读取的数据最大字节数
	//        &wCount, //DWORD*,用来接收返回成功读取的数据字节数
	//        NULL); //NULL为同步发送,OVERLAPPED*为异步发送
	//    if (!bReadStat)
	//    {
	//        return 0;
	//    }
	//    return wCount;
	//}
	//else
	{
		//异步方式,用同步会阻塞
		DWORD wCount = maxlen; //成功读取的数据字节数
		DWORD dwErrorFlags; //错误标志
		COMSTAT comStat; //通讯状态
		OVERLAPPED m_osRead; //异步输入输出结构体

							 //创建一个用于OVERLAPPED的事件处理,不会真正用到,但系统要求这么做
		memset(&m_osRead, 0, sizeof(m_osRead));
		m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, L"ReadEvent");

		ClearCommError(hCom, &dwErrorFlags, &comStat); //清除通讯错误,获得设备当前状态
		if (!comStat.cbInQue)return 0; //如果输入缓冲区字节数为0,则返回false

		BOOL bReadStat = ReadFile(hCom, //串口句柄
			buf, //数据首地址
			wCount, //要读取的数据最大字节数
			&wCount, //DWORD*,用来接收返回成功读取的数据字节数
			&m_osRead); //NULL为同步发送,OVERLAPPED*为异步发送
		if (!bReadStat)
		{
			if (GetLastError() == ERROR_IO_PENDING) //如果串口正在读取中
			{
				//GetOverlappedResult函数的最后一个参数设为TRUE
				//函数会一直等待,直到读操作完成或由于错误而返回
				GetOverlappedResult(hCom, &m_osRead, &wCount, TRUE);
			}
			else
			{
				ClearCommError(hCom, &dwErrorFlags, &comStat); //清除通讯错误
				CloseHandle(m_osRead.hEvent); //关闭并释放hEvent的内存
				return 0;
			}
		}
		return wCount;
	}
}

  

WzSerialPort.h:

 

#pragma once

#ifndef _WZSERIALPORT_H
#define _WZSERIALPORT_H

class WzSerialPort
{
public:
	WzSerialPort();
	~WzSerialPort();

	// 打开串口,成功返回true,失败返回false
	// portname(串口名): 在Windows下是"COM1""COM2"等,在Linux下是"/dev/ttyS1"等
	// baudrate(波特率): 9600、19200、38400、43000、56000、57600、115200 
	// parity(校验位): 0为无校验,1为奇校验,2为偶校验,3为标记校验(仅适用于windows)
	// databit(数据位): 4-8(windows),5-8(linux),通常为8位
	// stopbit(停止位): 1为1位停止位,2为2位停止位,3为1.5位停止位
	// synchronizeflag(同步、异步,仅适用与windows): 0为异步,1为同步
	bool open(const char* portname, int baudrate, char parity, char databit, char stopbit, char synchronizeflag = 1);

	//关闭串口,参数待定
	void close();

	//发送数据或写数据,成功返回发送数据长度,失败返回0
	int send(const void* buf, int len);

	//接受数据或读数据,成功返回读取实际数据的长度,失败返回0
	int receive(void* buf, int maxlen);

private:
	int pHandle[16];
	char synchronizeflag;
};

#endif

  

 SBC7835_DLL.cpp:

// SBC7835_DLL.cpp : 定义 DLL 应用程序的导出函数。
//

#include "pch.h"
#include "SBC7835_DLL.h"

WzSerialPort w;

uint8_t Check(uint8_t data[], uint8_t len)
{
	uint32_t sum = 0;
	uint8_t ret;
	for (uint8_t i = 0; i < len; i++)
	{
		sum += data[i];
	}
	ret = sum / len;
	return ret;
}

bool SBC7835_OpenCOM(const char* portname)
{
	return w.open(portname, 115200, 0, 8, 1);
}


int SBC7835_CtrlLEDS(uint32_t color)
{
	uint8_t sendData[6];
	uint8_t recData[6];
	int ret = 0;
	sendData[0] = 0xAA;
	sendData[1] = AllLEDCtrl;
	sendData[2] = color >> 16;
	sendData[3] = color >> 8;
	sendData[4] = color;
	sendData[5] = Check(sendData, 5);
	ret = w.send(sendData, 6);
	if (ret != 6)
	{
		return ret;
	}
	else
	{
		/*Sleep(10);
		ret = w.receive(recData, 6);
		if (ret != 6)
		{
			return false;
		}
		for (int i = 0; i < 6; i++)
		{
			if (recData[i] != sendData[i])
				return false;
		}*/
		return ret;
	}
}

bool SBC7835_CtrlOneLED(uint8_t num, uint8_t color)
{
	uint8_t sendData[6];
	uint8_t recData[6];
	int ret = 0;
	sendData[0] = 0xAA;
	sendData[1] = OneLEDCtrl;
	sendData[2] = num;
	sendData[3] = color;
	sendData[4] = 0xff;
	sendData[5] = Check(sendData, 5);
	ret = w.send(sendData, 6);
	if (ret != 6)
	{
		return false;
	}
	else
	{
		/*Sleep(10);
		ret = w.receive(recData, 6);
		if (ret != 6)
		{
			return false;
		}
		for (int i = 0; i < 6; i++)
		{
			if (recData[i] != sendData[i])
				return false;
		}*/
		return true;
	}
}

  

 SBC7835_DLL.h

#ifndef SBC7835_DLL_H
#define SBC7835_DLL_H

#include "pch.h"
#include <iostream>
#include "WzSerialPort.h"
#include "Windows.h"

#ifdef SBC7835_EXPORTS
#define SBC7835_API __declspec(dllexport) //声明为DLL导出函数的宏定义
#else
#define SBC7835_API __declspec(dllimport)
#endif



#define OneLEDCtrl		0x01
#define AllLEDCtrl		0x02


uint8_t Check(uint8_t data[], uint8_t len);
extern "C" SBC7835_API bool SBC7835_OpenCOM(const char* portname);
extern "C" SBC7835_API int SBC7835_CtrlLEDS(uint32_t color);
extern "C" SBC7835_API bool SBC7835_CtrlOneLED(uint8_t num, uint8_t color);

#endif

  

__declspec(dllexport)与__declspec(dllimport)是DLL内的关键字,表示导出和导入。

 dllexport是在这些类、函数以及数据的申明的时候使用。用他表明这些东西可以被外部函数使用,即(dllexport)是把 DLL中的相关代码(类,函数,数据)暴露出来为其他应用程序使用。使用了(dllexport)关键字,相当于声明了紧接在(dllexport)关键字后面的相关内容是可以为其他程序使用的。

      dllimport是在外部程序需要使用DLL内相关内容时使用的关键字。当一个外部程序要使用DLL 内部代码(类,函数,全局变量)时,只需要在程序内部使用(dllimport)关键字声明需要使用的代码就可以了,即(dllimport)关键字是在外部程序需要使用DLL内部相关内容的时候才使用。(dllimport)作用是把DLL中的相关代码插入到应用程序中。

      _declspec(dllexport)与_declspec(dllimport)是相互呼应,只有在DLL内部用dllexport作了声明,才能在外部函数中用dllimport导入相关代码。

 

 C#调用dll:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO.Ports;

namespace SBC7835_APP
{
    public partial class SBC7835 : Form
    {
        [DllImport("SBC7835_DLL.dll", EntryPoint = "SBC7835_OpenCOM", CallingConvention = CallingConvention.Cdecl)]
        public static extern bool SBC7835_OpenCOM(string portname);

        [DllImport("SBC7835_DLL.dll", EntryPoint = "SBC7835_CtrlLEDS", CallingConvention = CallingConvention.Cdecl)]
        public static extern bool SBC7835_CtrlLEDS(UInt32 color);

        [DllImport("SBC7835_DLL.dll", EntryPoint = "SBC7835_CtrlOneLED", CallingConvention = CallingConvention.Cdecl)]
        public static extern bool SBC7835_CtrlOneLED(byte num, byte color);

        int Count = 0;

        const byte LED1 = 0;
        const byte LED2 = 1;
        const byte LED3 = 2;
        const byte LED4 = 3;
        const byte LED5 = 4;
        const byte LED6 = 5;
        const byte LED7 = 6;
        const byte LED8 = 7;
        const byte LED9 = 8;
        const byte LED10 = 9;
        const byte LED11 = 10;
        const byte LED12 = 11;

        const byte LED_OFF = 0x00;
        const byte LED_RED = 0x01;
        const byte LED_GREEN = 0x02;
        const byte LED_BLUE = 0x03;

        public SBC7835()
        {
            InitializeComponent();
            string[] PortName = SerialPort.GetPortNames();
            for(int i = 0;i<PortName.Count();i++)
            {
                SerialPort_comboBox.Items.Add(PortName[i]);
            }
            
            LED1_comboBox.SelectedIndex = 0;
            LED2_comboBox.SelectedIndex = 0;
            LED3_comboBox.SelectedIndex = 0;
            LED4_comboBox.SelectedIndex = 0;
            LED5_comboBox.SelectedIndex = 0;
            LED6_comboBox.SelectedIndex = 0;
            LED7_comboBox.SelectedIndex = 0;
            LED8_comboBox.SelectedIndex = 0;
            LED9_comboBox.SelectedIndex = 0;
            LED10_comboBox.SelectedIndex = 0;
            LED11_comboBox.SelectedIndex = 0;
            LED12_comboBox.SelectedIndex = 0;
        }

        void OpenCOM()
        {
            string Com = SerialPort_comboBox.Text;
            try
            {
                if (SBC7835_OpenCOM(Com) != true)
                {
                    MessageBox.Show("SBC7835 Open COM Failed!", "Warning");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Open COM Error:" + ex.ToString(),
               "ERROR");
            }
        }

        private void Manual_button_Click(object sender, EventArgs e)
        {
            UInt32 color = 0;
            if (LED_OFF_radioButton.Checked == true)
                color = 0;
            else if (LED_RED_radioButton.Checked == true)
                color = 0x555555;
            else if (LED_GREEN_radioButton.Checked == true)
                color = 0xAAAAAA;
            else if (LED_BLUE_radioButton.Checked == true)
                color = 0xFFFFFF;
            try
            {
                if (SBC7835_CtrlLEDS((UInt32)color) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(),"ERROR");
            }
        }

        private void Auto_button_Click(object sender, EventArgs e)
        {
            timer1.Interval = 1000;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UInt32 color = 0;
            Count++;
            if (Count >= 4)
                Count = 0;
            if (Count == 0)
                color = 0;
            else if (Count == 1)
                color = 0x555555;
            else if (Count == 2)
                color = 0xAAAAAA;
            else if (Count == 3)
                color = 0xffffff;
            try
            {
                if (SBC7835_CtrlLEDS((UInt32)color) != true)
                {
                    if (Count == 0)
                    {
                        timer1.Stop();
                        return;
                    }                        
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");                    
                }                    
                else if(Count == 0)
                {
                    LED_OFF_radioButton.Checked = true;
                    timer1.Stop();
                }
                else if (Count == 1)
                {
                    LED_RED_radioButton.Checked = true;
                }
                else if (Count == 2)
                {
                    LED_GREEN_radioButton.Checked = true;
                }
                else if (Count == 3)
                {
                    LED_BLUE_radioButton.Checked = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
            
        }

        private void LED1_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED1,LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED1_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED1, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED1_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED1, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED1_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED1, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED2_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED2, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED2_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED2, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED2_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED2, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED2_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED2, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED3_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED3, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED3_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED3, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED3_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED3, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED3_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED3, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED4_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED4, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED4_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED4, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED4_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED4, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED4_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED4, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED5_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED5, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED5_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED5, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED5_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED5, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED5_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED5, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED6_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED6, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED6_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED6, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED6_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED6, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED6_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED6, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED7_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED7, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED7_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED7, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED7_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED7, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED7_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED7, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED8_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED8, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED8_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED8, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED8_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED8, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED8_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED8, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED9_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED9, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED9_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED9, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED9_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED9, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED9_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED9, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED10_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED10, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED10_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED10, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED10_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED10, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED10_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED10, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED11_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED11, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED11_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED11, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED11_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED11, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED11_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED11, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED12_OFF_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED12, LED_OFF) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED12_RED_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED12, LED_RED) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED12_GREEN_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED12, LED_GREEN) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void LED12_BLUE_radioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (SBC7835_CtrlOneLED(LED12, LED_BLUE) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(), "ERROR");
            }
        }

        private void All_LED_Ctrl_button_Click(object sender, EventArgs e)
        {
            Int32 color = 0;
            /*将所有LED灯的状态存放到color变量中,每一个LED的状态占用2个bit,如
           [bit1:bit0]
            * 表示LED1的状态,0表示熄灭,1表示红色,2表示绿色,3表示蓝色。其他
           的LED通理*/
            color |= (LED1_comboBox.SelectedIndex << (0 * 2));
            color |= (LED2_comboBox.SelectedIndex << (1 * 2));
            color |= (LED3_comboBox.SelectedIndex << (2 * 2));
            color |= (LED4_comboBox.SelectedIndex << (3 * 2));
            color |= (LED5_comboBox.SelectedIndex << (4 * 2));
            color |= (LED6_comboBox.SelectedIndex << (5 * 2));
            color |= (LED7_comboBox.SelectedIndex << (6 * 2));
            color |= (LED8_comboBox.SelectedIndex << (7 * 2));
            color |= (LED9_comboBox.SelectedIndex << (8 * 2));
            color |= (LED10_comboBox.SelectedIndex << (9 * 2));
            color |= (LED11_comboBox.SelectedIndex << (10 * 2));
            color |= (LED12_comboBox.SelectedIndex << (11 * 2));
            try
            {
                if (SBC7835_CtrlLEDS((UInt32)color) != true)
                    MessageBox.Show("SBC7835 Send CMD Failed", "Warning");
            }
            catch (Exception ex)
            {
                MessageBox.Show("SBC7835 Ctrl LEDS Error:" + ex.ToString(),
               "ERROR");
            }
        }

        private void OpenCOM_button_Click(object sender, EventArgs e)
        {
            OpenCOM();
        }
    }
}

 

 

过程中遇到过一个问题,就是串口发送数据的时候总会失败,但是其他项目中也是通过这种方式去实现串口通讯的,代码上应该没有问题,所以

 有点百思不得其解,直到我打开任务管理器,看到后台在运作的任务管理器中的串口助手,才知道串口被占用了。只要把串口助手关掉即可。

 

另外,C#上有一个简单的方法可以把设备上所有可用的串口列举出来的方法,代码如下:

using System.IO.Ports;
string[] PortName = SerialPort.GetPortNames();
            for(int i = 0;i<PortName.Count();i++)
            {
                SerialPort_comboBox.Items.Add(PortName[i]);
            }
               

 

posted @ 2022-01-21 01:57  沙河淘金  阅读(1174)  评论(0编辑  收藏  举报