#include "uart_process.h" wstring string2wstring(string str) { wstring result; //获取缓冲区大小,并申请空间,缓冲区大小按字符计算 int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0); TCHAR* buffer = new TCHAR[len + 1]; //多字节编码转换成宽字节编码 MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len); buffer[len] = '\0'; //添加字符串结尾 //删除缓冲区并返回值 result.append(buffer); delete[] buffer; return result; } std::string wstring2string(std::wstring wstr) { std::string result; //获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的 int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL); char* buffer = new char[len + 1]; //宽字节编码转换成多字节编码 WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL); buffer[len] = '\0'; //删除缓冲区并返回值 result.append(buffer); delete[] buffer; return result; } UartForm::UartForm(ui::Window* hwnd,std::wstring name, uint32_t baurate, uint8_t data_bits, uint8_t stop_bits, uint8_t verify, uint8_t flow_control): m_thread_recv(nullptr), mEditRecv(nullptr) { m_name = name; m_baurate = baurate; m_data_bits = data_bits; m_stop_bits = stop_bits; m_verify = verify; m_flow_contro = flow_control; m_runing = true; m_thread_recv = new std::thread([this]() { UINT PortNum = 0; for (int i = 3; m_name[i] != '\0'; i++) //转换为数字 { PortNum = PortNum * 10 + (m_name[i] - '0'); } char recv[1024] = {0}; while (this->m_runing) { if (0 < SerialPort::ReadPort(PortNum, recv, 1024)) { printf("recv data: %s", recv); this->m_show_recv += string2wstring(recv); ::PostMessage(this->GetWindow()->GetHWND(), WM_ADD_UART_RECVDATA, 0, 0); } else { Sleep(30); } } }); if (nullptr != hwnd) { this->SetWindow(hwnd, nullptr, false); } } void UartForm::OnUpdateUart() { if(mEditRecv != nullptr) this->mEditRecv->SetText(this->m_show_recv.c_str()); } void UartForm::Init() { ui::ChildBox::Init(); auto mRightSide = dynamic_cast (FindSubControl(L"uart_info_label")); wchar_t p[100] = { 0 }; wsprintf(p,L"串口号: %s 波特率%d 数据位: %d 停止位: %d ", m_name.c_str(),m_baurate, m_data_bits,m_stop_bits); mRightSide->SetText(std::wstring(p)); mEditSend = dynamic_cast(FindSubControl(L"uart_send_edit")); mEditRecv = dynamic_cast(FindSubControl(L"uart_recv_eidt")); mEditRecv->SetReadOnly(true); auto mBtnSend = static_cast(FindSubControl(L"btn_send_data")); if (mBtnSend != nullptr) { mBtnSend->AttachClick([this](ui::EventArgs*) { UINT PortNum = 0; for (int i = 3; m_name[i] != '\0'; i++) //转换为数字 { PortNum = PortNum * 10 + (m_name[i] - '0'); } auto x = mEditSend->GetText(); auto tmp = wstring2string(x); wprintf(L"%s\r\n", x.c_str()); SerialPort::WritePort(PortNum, tmp.c_str(), tmp.size()); return true; }); } } void UartForm::UpdateRecvEdit() { } void UartForm::HandleMessage(ui::EventArgs& msg) { printf("0x%x \r\n", msg.Type); if (msg.Type == WM_ADD_UART_RECVDATA) { printf("hello world\r\n"); this->mEditRecv->SetText(L"123"); } this->mEditRecv->SetText(this->m_show_recv.c_str()); }