Repository: Zhou-zhi-peng/SerialPortForWindowsTerminal Branch: main Commit: a55edef8a1da Files: 12 Total size: 56.8 KB Directory structure: gitextract_0n30jf_a/ ├── .gitignore ├── LICENSE ├── README.md ├── SerialForWindowsTerminal.cpp ├── SerialForWindowsTerminal.h ├── SerialForWindowsTerminal.rc ├── SerialForWindowsTerminal.sln ├── SerialForWindowsTerminal.vcxproj ├── SerialForWindowsTerminal.vcxproj.filters ├── framework.h ├── resource.h └── targetver.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.rsuser *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Mono auto generated files mono_crash.* # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ [Ll]ogs/ # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # Visual Studio 2017 auto generated files Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUnit *.VisualState.xml TestResult.xml nunit-*.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ # StyleCop StyleCopReport.xml # Files built by Visual Studio *_i.c *_p.c *_h.h *.ilk *.meta *.obj *.iobj *.pch *.pdb *.ipdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *_wpftmp.csproj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # Visual Studio Trace Files *.e2e # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # NuGet Symbol Packages *.snupkg # The packages folder can be ignored because of Package Restore **/[Pp]ackages/* # except build/, which is used as an MSBuild target. !**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx *.appxbundle *.appxupload # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !?*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Including strong name files can present a security risk # (https://github.com/github/gitignore/pull/2483#issue-259490424) #*.snk # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ *.rptproj.bak # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings *.rptproj.rsuser *- [Bb]ackup.rdl *- [Bb]ackup ([0-9]).rdl *- [Bb]ackup ([0-9][0-9]).rdl # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # CodeRush personal settings .cr/personal # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # OpenCover UI analysis results OpenCover/ # Azure Stream Analytics local run output ASALocalRun/ # MSBuild Binary and Structured Log *.binlog # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder .mfractor/ # Local History for Visual Studio .localhistory/ # BeatPulse healthcheck temp database healthchecksdb # Backup folder for Package Reference Convert tool in Visual Studio 2017 MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder .ionide/ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # SerialPortForWindowsTerminal Serial port for windows terminal, 让Windows Terminal支持串口的插件 该插件为WindowsTerminal提供访问串口终端能力 ## 使用说明 ![截图](https://github.com/Zhou-zhi-peng/SerialPortForWindowsTerminal/blob/main/images/001.bmp?raw=true) ![截图](https://github.com/Zhou-zhi-peng/SerialPortForWindowsTerminal/blob/main/images/002.bmp?raw=true) ![截图](https://github.com/Zhou-zhi-peng/SerialPortForWindowsTerminal/blob/main/images/003.bmp?raw=true) ## 配置说明: ![使用说明](https://github.com/Zhou-zhi-peng/SerialPortForWindowsTerminal/blob/main/images/000.gif?raw=true) ================================================ FILE: SerialForWindowsTerminal.cpp ================================================ // SerialForWindowsTerminal.cpp : 定义应用程序的入口点。 // #include "framework.h" #include "SerialForWindowsTerminal.h" #include #include #include #include #include #define MAX_LOADSTRING 100 // 全局变量: HINSTANCE hInstance; INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK SettingFunc(HWND, UINT, WPARAM, LPARAM); // 添加全局标志来跟踪Ctrl+A状态 bool g_isCtrlAPressed = false; // 添加全局标志来控制程序退出 bool g_shouldExit = false; std::vector g_lineBuffer; using PortsArray = std::vector>; static PortsArray GetAllPorts(void) { PortsArray ports; HKEY hRegKey; int nCount = 0; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Hardware\\DeviceMap\\SerialComm", 0, KEY_READ, &hRegKey) == ERROR_SUCCESS) { while (true) { TCHAR szName[MAX_PATH] = { 0 }; TCHAR szPort[MAX_PATH] = { 0 }; DWORD nValueSize = MAX_PATH - 1; DWORD nDataSize = MAX_PATH - 1; DWORD nType; if (::RegEnumValue(hRegKey, nCount, szName, &nValueSize, NULL, &nType, (LPBYTE)szPort, &nDataSize) == ERROR_NO_MORE_ITEMS) { break; } std::wstring name(szName); auto idx = name.find_last_of('\\'); if (idx != name.npos) { name = name.substr(idx + 1); } name += L" ("; name += szPort; name += L")"; ports.push_back(std::make_pair(name, (int)std::wcstoul(szPort + 3, nullptr, 10))); nCount++; } ::RegCloseKey(hRegKey); } return ports; } static void UpdatePortControl(HWND hDlg) { auto allPorts = GetAllPorts(); auto hWndPort = GetDlgItem(hDlg, IDC_COMBO_PORT); ComboBox_ResetContent(hWndPort); for (auto port : allPorts) { auto index = ComboBox_AddString(hWndPort, port.first.c_str()); ComboBox_SetItemData(hWndPort, index, port.second); } } static void CenterParentWindow(HWND hWnd) { RECT rcDlg; ::GetWindowRect(hWnd, &rcDlg); RECT rcParent; HWND hWndParent = GetParent(hWnd); GetClientRect(hWndParent, &rcParent); POINT ptParentInScreen; ptParentInScreen.x = rcParent.left; ptParentInScreen.y = rcParent.top; ::ClientToScreen(hWndParent, (LPPOINT)&ptParentInScreen); SetWindowPos( hWnd, NULL, ptParentInScreen.x + (rcParent.right - rcParent.left - (rcDlg.right - rcDlg.left)) / 2, ptParentInScreen.y + (rcParent.bottom - rcParent.top - (rcDlg.bottom - rcDlg.top)) / 2, 0, 0, SWP_NOZORDER | SWP_NOSIZE); } typedef struct { DWORD Serial; DWORD BaudRate; DWORD WordLength; DWORD StopBit; DWORD Parity; DWORD FlowControl; DWORD EncodingFormat; // 添加编码格式字段:0=UTF8, 1=GBK DWORD EchoMode; // 添加回显模式字段:0=关闭(字符模式), 1=开启(行模式) }SERIAL_CONFIG; static void WriteSerialConfig(const SERIAL_CONFIG& cfg) { HKEY hKey; if (ERROR_SUCCESS == ::RegCreateKey(HKEY_CURRENT_USER, L"SOFTWARE\\SerialForWindowsTerminal", &hKey)) { DWORD dwSize = sizeof(DWORD); DWORD dwType = REG_DWORD; ::RegSetValueEx(hKey, L"Serial", 0, dwType, (CONST LPBYTE)&cfg.Serial, dwSize); ::RegSetValueEx(hKey, L"BaudRate", 0, dwType, (CONST LPBYTE)&cfg.BaudRate, dwSize); ::RegSetValueEx(hKey, L"WordLength", 0, dwType, (CONST LPBYTE)&cfg.WordLength, dwSize); ::RegSetValueEx(hKey, L"StopBit", 0, dwType, (CONST LPBYTE)&cfg.StopBit, dwSize); ::RegSetValueEx(hKey, L"Parity", 0, dwType, (CONST LPBYTE)&cfg.Parity, dwSize); ::RegSetValueEx(hKey, L"FlowControl", 0, dwType, (CONST LPBYTE)&cfg.FlowControl, dwSize); ::RegSetValueEx(hKey, L"EncodingFormat", 0, dwType, (CONST LPBYTE)&cfg.EncodingFormat, dwSize); ::RegSetValueEx(hKey, L"EchoMode", 0, dwType, (CONST LPBYTE)&cfg.EchoMode, dwSize); // 写入回显模式 ::RegCloseKey(hKey); } } static void ToggleEncodingFormat(SERIAL_CONFIG& cfg) { // 切换编码格式 cfg.EncodingFormat = (cfg.EncodingFormat == 0) ? 1 : 0; // 应用新的编码格式 if (cfg.EncodingFormat == 0) // UTF-8 { SetConsoleOutputCP(CP_UTF8); SetConsoleCP(CP_UTF8); std::cout << "\033[32mConsole encoding: UTF-8\033[0m" << std::endl; } else // GBK { SetConsoleOutputCP(936); SetConsoleCP(936); std::cout << "\033[32mConsole encoding: GBK\033[0m" << std::endl; } // 保存配置到注册表 WriteSerialConfig(cfg); } static SERIAL_CONFIG ReadSerialConfig() { HKEY hKey; SERIAL_CONFIG cfg; cfg.Serial = 0; cfg.BaudRate = 9600; cfg.WordLength = 8; cfg.StopBit = ONESTOPBIT; cfg.Parity = NOPARITY; cfg.FlowControl = 0; cfg.EncodingFormat = 0; // 默认使用UTF-8编码 cfg.EchoMode = 0; // 默认关闭回显模式(字符模式) if (ERROR_SUCCESS == ::RegOpenKeyEx(HKEY_CURRENT_USER, L"SOFTWARE\\SerialForWindowsTerminal", 0, KEY_READ, &hKey)) { DWORD dwSize = sizeof(DWORD); DWORD dwType = REG_DWORD; ::RegQueryValueEx(hKey, L"Serial", 0, &dwType, (LPBYTE)&cfg.Serial, &dwSize); ::RegQueryValueEx(hKey, L"BaudRate", 0, &dwType, (LPBYTE)&cfg.BaudRate, &dwSize); ::RegQueryValueEx(hKey, L"WordLength", 0, &dwType, (LPBYTE)&cfg.WordLength, &dwSize); ::RegQueryValueEx(hKey, L"StopBit", 0, &dwType, (LPBYTE)&cfg.StopBit, &dwSize); ::RegQueryValueEx(hKey, L"Parity", 0, &dwType, (LPBYTE)&cfg.Parity, &dwSize); ::RegQueryValueEx(hKey, L"FlowControl", 0, &dwType, (LPBYTE)&cfg.FlowControl, &dwSize); ::RegQueryValueEx(hKey, L"EncodingFormat", 0, &dwType, (LPBYTE)&cfg.EncodingFormat, &dwSize); ::RegQueryValueEx(hKey, L"EchoMode", 0, &dwType, (LPBYTE)&cfg.EchoMode, &dwSize); // 读取回显模式 ::RegCloseKey(hKey); } return cfg; } static void ToggleEchoMode(SERIAL_CONFIG& cfg) { // 切换回显模式 cfg.EchoMode = (cfg.EchoMode == 0) ? 1 : 0; // 清空行缓冲区 g_lineBuffer.clear(); // 显示当前回显模式 std::cout << "\033[32mEcho mode: " << (cfg.EchoMode == 0 ? "Off" : "On") << "\033[0m" << std::endl; // 保存配置到注册表 WriteSerialConfig(cfg); } static boost::system::error_code InitializeSerialPort(boost::asio::serial_port& serialPort,const SERIAL_CONFIG& cfg, boost::system::error_code& ec) { serialPort.set_option(boost::asio::serial_port::baud_rate(cfg.BaudRate), ec); if (ec) return ec; serialPort.set_option(boost::asio::serial_port::character_size(cfg.WordLength), ec); if (ec) return ec; switch (cfg.StopBit) { case 0: serialPort.set_option(boost::asio::serial_port::stop_bits(boost::asio::serial_port::stop_bits::one), ec); break; case 1: serialPort.set_option(boost::asio::serial_port::stop_bits(boost::asio::serial_port::stop_bits::onepointfive), ec); break; case 2: serialPort.set_option(boost::asio::serial_port::stop_bits(boost::asio::serial_port::stop_bits::two), ec); break; default: serialPort.set_option(boost::asio::serial_port::stop_bits(boost::asio::serial_port::stop_bits::one), ec); break; } if (ec) return ec; switch (cfg.Parity) { case 0: serialPort.set_option(boost::asio::serial_port::parity(boost::asio::serial_port::parity::none), ec); break; case 1: serialPort.set_option(boost::asio::serial_port::parity(boost::asio::serial_port::parity::odd), ec); break; case 2: serialPort.set_option(boost::asio::serial_port::parity(boost::asio::serial_port::parity::even), ec); break; default: serialPort.set_option(boost::asio::serial_port::parity(boost::asio::serial_port::parity::none), ec); break; } if (ec) return ec; switch (cfg.FlowControl) { case 0: serialPort.set_option(boost::asio::serial_port::flow_control(boost::asio::serial_port::flow_control::none), ec); break; case 1: serialPort.set_option(boost::asio::serial_port::flow_control(boost::asio::serial_port::flow_control::software), ec); break; case 2: serialPort.set_option(boost::asio::serial_port::flow_control(boost::asio::serial_port::flow_control::hardware), ec); break; default: serialPort.set_option(boost::asio::serial_port::flow_control(boost::asio::serial_port::flow_control::none), ec); break; } return ec; } template static void DoStreamToStream(TStream1& stream1, TStream2& stream2, std::vector& buffer, SERIAL_CONFIG* pCfg = nullptr) { stream1.async_read_some( boost::asio::buffer(buffer.data(), buffer.size()), [&stream1, &stream2, &buffer, pCfg](const boost::system::error_code& ec, std::size_t bytes_transferred) { if (ec) { std::cerr << "\033[31m" << "error : " << ec.message() << "\033[0m" << std::endl; } else { // 检查是否需要特殊处理键盘输入(仅当stream1是标准输入且有配置指针时) bool skipWrite = false; if (pCfg != nullptr) { for (size_t i = 0; i < bytes_transferred; i++) { uint8_t ch = buffer[i]; // 检查Ctrl+A (ASCII 1) if (ch == 1) { g_isCtrlAPressed = true; skipWrite = true; break; } // 如果Ctrl+A已按下,检查后续按键 if (g_isCtrlAPressed) { g_isCtrlAPressed = false; // 重置标志 skipWrite = true; // Ctrl+X: 退出程序 if (ch == 24) // Ctrl+X { if (MessageBoxW(NULL, L"确定要退出程序吗?", L"退出确认", MB_YESNO | MB_ICONQUESTION) == IDYES) { g_shouldExit = true; // 通过取消所有异步操作来退出io_service stream1.cancel(); stream2.cancel(); exit(0); } } // Ctrl+C: 切换编码格式 else if (ch == 3) // Ctrl+C { ToggleEncodingFormat(*pCfg); } // Ctrl+E: 切换回显模式 else if (ch == 5) // Ctrl+E { ToggleEchoMode(*pCfg); } break; } } // 如果是回显模式且不是特殊按键,进行行缓冲处理 if (!skipWrite && pCfg->EchoMode == 1) { skipWrite = true; // 总是跳过直接写入,由行模式处理 for (size_t i = 0; i < bytes_transferred; i++) { uint8_t ch = buffer[i]; // 处理退格键 if (ch == 8 || ch == 127) // Backspace或Delete { if (!g_lineBuffer.empty()) { g_lineBuffer.pop_back(); // 输出退格、空格、退格以清除屏幕上的字符 std::cout << "\b \b"; } continue; } // 处理回车换行 if (ch == '\r' || ch == '\n') { // 发送累积的行数据 // if (!g_lineBuffer.empty()) // { // 添加回车换行 g_lineBuffer.push_back('\r'); g_lineBuffer.push_back('\n'); // 写入串口 boost::asio::write(stream2, boost::asio::buffer(g_lineBuffer.data(), g_lineBuffer.size())); // 清空缓冲区 g_lineBuffer.clear(); // } // 显示换行到终端 std::cout << "\n"; continue; } // 普通字符,添加到缓冲区并回显 g_lineBuffer.push_back(ch); std::cout << static_cast(ch); std::cout.flush(); // 确保立即显示 } } } // 只有在不需要特殊处理且不是回显模式时才进行正常的数据流传输 if (!skipWrite && (pCfg == nullptr || pCfg->EchoMode == 0)) { boost::asio::async_write( stream2, boost::asio::const_buffer(buffer.data(), bytes_transferred), [&stream1, &stream2, &buffer, pCfg](const boost::system::error_code& ec, std::size_t bytes_transferred) { if (ec) { std::cerr << "\033[31m" << "error : " << ec.message() << "\033[0m" << std::endl; } else { DoStreamToStream(stream1, stream2, buffer, pCfg); } } ); } else if (!g_shouldExit) { // 继续监听输入 DoStreamToStream(stream1, stream2, buffer, pCfg); } } } ); } static boost::system::error_code DoWork(boost::asio::io_service& ioctx, boost::asio::serial_port& serialPort, SERIAL_CONFIG& cfg) { boost::system::error_code ec; boost::asio::windows::stream_handle stdinput(ioctx); boost::asio::windows::stream_handle stdoutput(ioctx); const auto kBufferSize = 1024; std::vector serialPortRecvBuffer; std::vector serialPortSendBuffer; serialPortRecvBuffer.resize(kBufferSize); serialPortSendBuffer.resize(kBufferSize); auto conin = CreateFile(L"CONIN$", FILE_GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); auto conout = CreateFile(L"CONOUT$", FILE_GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0); if (stdinput.assign(conin, ec)) return ec; if (stdoutput.assign(conout, ec)) return ec; // 对于串口到输出的流,不需要特殊处理 DoStreamToStream(serialPort, stdoutput, serialPortRecvBuffer); // 对于输入到串口的流,传递配置指针以支持快捷键处理 DoStreamToStream(stdinput, serialPort, serialPortSendBuffer, &cfg); // 重置退出标志 g_shouldExit = false; ioctx.run(ec); return ec; } int wmain(int argc, const WCHAR* args[]) { boost::system::error_code ec; boost::asio::io_service ioctx; boost::asio::serial_port serialPort(ioctx); hInstance = GetModuleHandle(nullptr); DWORD consoleMode = 0; auto conin = GetStdHandle(STD_INPUT_HANDLE); auto conout = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleMode(conin, &consoleMode); consoleMode |= ENABLE_MOUSE_INPUT; consoleMode &= ~ENABLE_ECHO_INPUT; consoleMode &= ~ENABLE_PROCESSED_INPUT; consoleMode &= ~ENABLE_LINE_INPUT; consoleMode |= ENABLE_QUICK_EDIT_MODE; consoleMode |= ENABLE_WINDOW_INPUT; consoleMode |= ENABLE_VIRTUAL_TERMINAL_INPUT; SetConsoleMode(conin, consoleMode); GetConsoleMode(conout, &consoleMode); SetConsoleMode(conout, consoleMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT); while (true) { auto hWndParent = ::GetForegroundWindow(); if (hWndParent == nullptr) hWndParent = GetConsoleWindow(); if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_SETTING_DIALOG), hWndParent, SettingFunc, 1) == IDOK) { ioctx.restart(); auto cfg = ReadSerialConfig(); auto portName = std::string("COM") + std::to_string(cfg.Serial); if (serialPort.open(portName, ec)) { std::cerr << "\033[31m" << "can not open " << portName << "\033[0m" <= 0) { cfg.Serial = (DWORD)ComboBox_GetItemData(hWndPort, curSel); } else { ComboBox_GetText(hWndPort, txtBuffer, 32); cfg.Serial = std::wcstoul(txtBuffer + 3, nullptr, 10); } ComboBox_GetText(hWndBaudRate, txtBuffer, 32); cfg.BaudRate = std::wcstoul(txtBuffer, nullptr, 10); cfg.WordLength = ComboBox_GetCurSel(hWndWordLength) + 4; cfg.StopBit = ComboBox_GetCurSel(hWndStopBit); cfg.Parity = ComboBox_GetCurSel(hWndParity); cfg.FlowControl = ComboBox_GetCurSel(hWndFlowControl); // 获取编码格式下拉框的当前选择 auto hWndEncoding = GetDlgItem(hDlg, IDC_COMBO_ENCODING); cfg.EncodingFormat = ComboBox_GetCurSel(hWndEncoding); // 获取回显模式复选框状态 auto hWndEchoMode = GetDlgItem(hDlg, IDC_COMBO_ECHO); cfg.EchoMode = ComboBox_GetCurSel(hWndEchoMode); WriteSerialConfig(cfg); } EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } ================================================ FILE: SerialForWindowsTerminal.h ================================================ #pragma once #include "resource.h" ================================================ FILE: SerialForWindowsTerminal.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.31019.35 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SerialForWindowsTerminal", "SerialForWindowsTerminal.vcxproj", "{77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}.Debug|x64.ActiveCfg = Debug|x64 {77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}.Debug|x64.Build.0 = Debug|x64 {77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}.Debug|x86.ActiveCfg = Debug|Win32 {77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}.Debug|x86.Build.0 = Debug|Win32 {77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}.Release|x64.ActiveCfg = Release|x64 {77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}.Release|x64.Build.0 = Release|x64 {77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}.Release|x86.ActiveCfg = Release|Win32 {77CF1E9C-BB5B-4DD5-B18C-30D998DB8BC0}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7BB5C9B7-34E8-4227-B1EB-22E406EEF0EA} EndGlobalSection EndGlobal ================================================ FILE: SerialForWindowsTerminal.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 Win32Proj {77cf1e9c-bb5b-4dd5-b18c-30d998db8bc0} SerialForWindowsTerminal 10.0 Application true v142 Unicode Application false v142 true Unicode Application true v142 Unicode Application false v142 true Unicode true false true false Level3 true WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) true D:\boost_1_68_0\ MultiThreadedDebug Console true type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*' D:\boost_1_68_0\Windows\msvc14.1\lib;%(AdditionalLibraryDirectories) PerMonitorHighDPIAware Level3 true true true WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) true C:\local\boost_1_68_0\lib64-msvc-14.1;C:\local\boost_1_68_0 MultiThreaded Console true true true type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*' C:\local\boost_1_68_0\lib64-msvc-14.1;%(AdditionalLibraryDirectories) Level3 true _DEBUG;_WINDOWS;%(PreprocessorDefinitions) true C:\local\boost_1_68_0 MultiThreadedDebug Console true C:\local\boost_1_68_0\lib64-msvc-14.1;%(AdditionalLibraryDirectories) type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*' Level3 true true true NDEBUG;_WINDOWS;%(PreprocessorDefinitions) true C:\local\boost_1_68_0 MultiThreaded Console true true true C:\local\boost_1_68_0\lib64-msvc-14.1;%(AdditionalLibraryDirectories) type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*' ================================================ FILE: SerialForWindowsTerminal.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 头文件 头文件 头文件 头文件 源文件 资源文件 资源文件 资源文件 ================================================ FILE: framework.h ================================================ // header.h: 标准系统包含文件的包含文件, // 或特定于项目的包含文件 // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容 // Windows 头文件 #include #include // C 运行时头文件 #include #include #include #include ================================================ FILE: resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ 生成的包含文件。 // 供 SerialForWindowsTerminal.rc 使用 // #define IDC_MYICON 2 #define IDD_SERIALFORWINDOWSTERMINAL_DIALOG 102 #define IDS_APP_TITLE 103 #define IDD_ABOUTBOX 103 #define IDM_ABOUT 104 #define IDI_SERIALFORWINDOWSTERMINAL 107 #define IDI_SMALL 108 #define IDC_SERIALFORWINDOWSTERMINAL 109 #define IDR_MAINFRAME 128 #define IDD_SETTING_DIALOG 130 #define IDC_COMBO1 1002 #define IDC_COMBO_PORT 1002 #define IDC_COMBO2 1003 #define IDC_COMBO_SPEED 1003 #define IDC_COMBO3 1004 #define IDC_COMBO_WORD 1004 #define IDC_COMBO4 1005 #define IDC_COMBO_STOP 1005 #define IDC_COMBO5 1006 #define IDC_COMBO_CHECK 1006 #define IDC_COMBO_PARITY 1006 #define IDC_COMBO6 1007 #define IDC_COMBO_FLOW_CONTROL 1007 #define IDC_COMBO_ENCODING 1008 #define IDC_COMBO_FLOW_CONTROL2 1011 #define IDC_COMBO_ECHO 1011 #define IDC_STATIC -1 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 131 #define _APS_NEXT_COMMAND_VALUE 32771 #define _APS_NEXT_CONTROL_VALUE 1010 #define _APS_NEXT_SYMED_VALUE 110 #endif #endif ================================================ FILE: targetver.h ================================================ #pragma once // // 包含 SDKDDKVer.h 可定义可用的最高版本的 Windows 平台。 // 如果希望为之前的 Windows 平台构建应用程序,在包含 SDKDDKVer.h 之前请先包含 WinSDKVer.h 并 // 将 _WIN32_WINNT 宏设置为想要支持的平台。 #include