├── image
└── UIsnip.png
├── SerialCommunication.v11.suo
├── SerialCommunication
├── bin
│ └── Debug
│ │ ├── Cfg.ini
│ │ ├── SerialConfig.ini
│ │ ├── SerialCommunication.exe
│ │ ├── SerialCommunication.pdb
│ │ ├── SerialCommunication.vshost.exe
│ │ ├── SerialCommunication.exe.config
│ │ ├── SerialCommunication.vshost.exe.config
│ │ └── SerialCommunication.vshost.exe.manifest
├── obj
│ └── Debug
│ │ ├── SerialCommunication.exe
│ │ ├── SerialCommunication.pdb
│ │ ├── SerialCommunication.Form1.resources
│ │ ├── DesignTimeResolveAssemblyReferences.cache
│ │ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ │ ├── SerialCommunication.Properties.Resources.resources
│ │ ├── SerialCommunication.csproj.GenerateResource.Cache
│ │ ├── SerialCommunication.csprojResolveAssemblyReference.cache
│ │ └── SerialCommunication.csproj.FileListAbsolute.txt
├── App.config
├── Properties
│ ├── Settings.settings
│ ├── AssemblyInfo.cs
│ ├── Settings.Designer.cs
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── Program.cs
├── Profile.cs
├── SerialCommunication.csproj
├── Form1.resx
├── IniFile.cs
├── ModbusCRC16.cs
├── Form1.Designer.cs
└── Form1.cs
├── INIFileTest
├── bin
│ └── Debug
│ │ ├── FileConfig.ini
│ │ ├── INIFileTest.exe
│ │ ├── INIFileTest.pdb
│ │ ├── INIFileTest.vshost.exe
│ │ ├── INIFileTest.exe.config
│ │ ├── INIFileTest.vshost.exe.config
│ │ └── INIFileTest.vshost.exe.manifest
├── obj
│ └── Debug
│ │ ├── INIFileTest.exe
│ │ ├── INIFileTest.pdb
│ │ ├── INIFileTest.Form1.resources
│ │ ├── INIFileTest.csproj.GenerateResource.Cache
│ │ ├── INIFileTest.Properties.Resources.resources
│ │ ├── DesignTimeResolveAssemblyReferencesInput.cache
│ │ ├── INIFileTest.csprojResolveAssemblyReference.cache
│ │ └── INIFileTest.csproj.FileListAbsolute.txt
├── App.config
├── Properties
│ ├── Settings.settings
│ ├── AssemblyInfo.cs
│ ├── Settings.Designer.cs
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── Program.cs
├── Profile.cs
├── INIFileTest.csproj
├── Form1.cs
├── Form1.resx
├── IniFile.cs
└── Form1.Designer.cs
├── README.md
└── SerialCommunication.sln
/image/UIsnip.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/image/UIsnip.png
--------------------------------------------------------------------------------
/SerialCommunication.v11.suo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication.v11.suo
--------------------------------------------------------------------------------
/SerialCommunication/bin/Debug/Cfg.ini:
--------------------------------------------------------------------------------
1 | [CONFIG]
2 | BaudRate=9600
3 | DataBits=8
4 | StopBits=1
5 | G_PARITY=NONE
6 |
--------------------------------------------------------------------------------
/SerialCommunication/bin/Debug/SerialConfig.ini:
--------------------------------------------------------------------------------
1 | [CONFIG]
2 | BaudRate=9600
3 |
4 | DataBits=8
5 | StopBits=1
6 | G_PARITY=NONE
7 |
--------------------------------------------------------------------------------
/INIFileTest/bin/Debug/FileConfig.ini:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/bin/Debug/FileConfig.ini
--------------------------------------------------------------------------------
/INIFileTest/bin/Debug/INIFileTest.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/bin/Debug/INIFileTest.exe
--------------------------------------------------------------------------------
/INIFileTest/bin/Debug/INIFileTest.pdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/bin/Debug/INIFileTest.pdb
--------------------------------------------------------------------------------
/INIFileTest/obj/Debug/INIFileTest.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/obj/Debug/INIFileTest.exe
--------------------------------------------------------------------------------
/INIFileTest/obj/Debug/INIFileTest.pdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/obj/Debug/INIFileTest.pdb
--------------------------------------------------------------------------------
/INIFileTest/bin/Debug/INIFileTest.vshost.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/bin/Debug/INIFileTest.vshost.exe
--------------------------------------------------------------------------------
/INIFileTest/obj/Debug/INIFileTest.Form1.resources:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/obj/Debug/INIFileTest.Form1.resources
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | SerialCommunication
2 | ====================
3 | c#写的串口通信,使用的winform。
4 | 实现了16进制和字符串的收发。
5 | 详情见:https://github.com/changhr2013/SerialCommunication/wiki
6 |
--------------------------------------------------------------------------------
/SerialCommunication/bin/Debug/SerialCommunication.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/bin/Debug/SerialCommunication.exe
--------------------------------------------------------------------------------
/SerialCommunication/bin/Debug/SerialCommunication.pdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/bin/Debug/SerialCommunication.pdb
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/SerialCommunication.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/obj/Debug/SerialCommunication.exe
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/SerialCommunication.pdb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/obj/Debug/SerialCommunication.pdb
--------------------------------------------------------------------------------
/SerialCommunication/bin/Debug/SerialCommunication.vshost.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/bin/Debug/SerialCommunication.vshost.exe
--------------------------------------------------------------------------------
/INIFileTest/obj/Debug/INIFileTest.csproj.GenerateResource.Cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/obj/Debug/INIFileTest.csproj.GenerateResource.Cache
--------------------------------------------------------------------------------
/INIFileTest/obj/Debug/INIFileTest.Properties.Resources.resources:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/obj/Debug/INIFileTest.Properties.Resources.resources
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/SerialCommunication.Form1.resources:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/obj/Debug/SerialCommunication.Form1.resources
--------------------------------------------------------------------------------
/INIFileTest/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache
--------------------------------------------------------------------------------
/INIFileTest/obj/Debug/INIFileTest.csprojResolveAssemblyReference.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/INIFileTest/obj/Debug/INIFileTest.csprojResolveAssemblyReference.cache
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/DesignTimeResolveAssemblyReferences.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/obj/Debug/DesignTimeResolveAssemblyReferences.cache
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache
--------------------------------------------------------------------------------
/INIFileTest/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/SerialCommunication.Properties.Resources.resources:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/obj/Debug/SerialCommunication.Properties.Resources.resources
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/SerialCommunication.csproj.GenerateResource.Cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/obj/Debug/SerialCommunication.csproj.GenerateResource.Cache
--------------------------------------------------------------------------------
/SerialCommunication/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/SerialCommunication.csprojResolveAssemblyReference.cache:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/changhr2013/SerialCommunication/HEAD/SerialCommunication/obj/Debug/SerialCommunication.csprojResolveAssemblyReference.cache
--------------------------------------------------------------------------------
/INIFileTest/bin/Debug/INIFileTest.exe.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/INIFileTest/bin/Debug/INIFileTest.vshost.exe.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/SerialCommunication/bin/Debug/SerialCommunication.exe.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/SerialCommunication/bin/Debug/SerialCommunication.vshost.exe.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/INIFileTest/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/SerialCommunication/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/INIFileTest/bin/Debug/INIFileTest.vshost.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/SerialCommunication/bin/Debug/SerialCommunication.vshost.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/INIFileTest/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using System.Windows.Forms;
6 |
7 | namespace INIFileTest
8 | {
9 | static class Program
10 | {
11 | ///
12 | /// 应用程序的主入口点。
13 | ///
14 | [STAThread]
15 | static void Main()
16 | {
17 | Application.EnableVisualStyles();
18 | Application.SetCompatibleTextRenderingDefault(false);
19 | Application.Run(new Form1());
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/SerialCommunication/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using System.Windows.Forms;
6 |
7 | namespace SerialCommunication
8 | {
9 | static class Program
10 | {
11 | ///
12 | /// 应用程序的主入口点。
13 | ///
14 | [STAThread]
15 | static void Main()
16 | {
17 | Application.EnableVisualStyles();
18 | Application.SetCompatibleTextRenderingDefault(false);
19 | Application.Run(new Form1());
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/INIFileTest/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("INIFileTest")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("INIFileTest")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("19667e0a-0d92-4b77-aff4-85a3208dd952")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/INIFileTest/obj/Debug/INIFileTest.csproj.FileListAbsolute.txt:
--------------------------------------------------------------------------------
1 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\bin\Debug\INIFileTest.exe.config
2 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\bin\Debug\INIFileTest.exe
3 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\bin\Debug\INIFileTest.pdb
4 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\obj\Debug\INIFileTest.Form1.resources
5 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\obj\Debug\INIFileTest.Properties.Resources.resources
6 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\obj\Debug\INIFileTest.csproj.GenerateResource.Cache
7 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\obj\Debug\INIFileTest.exe
8 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\obj\Debug\INIFileTest.pdb
9 | C:\Users\admin\documents\visual studio 2012\Projects\SerialCommunication\INIFileTest\obj\Debug\INIFileTest.csprojResolveAssemblyReference.cache
10 |
--------------------------------------------------------------------------------
/SerialCommunication/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // 有关程序集的常规信息通过以下
6 | // 特性集控制。更改这些特性值可修改
7 | // 与程序集关联的信息。
8 | [assembly: AssemblyTitle("SerialCommunication")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("Microsoft")]
12 | [assembly: AssemblyProduct("SerialCommunication")]
13 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // 将 ComVisible 设置为 false 使此程序集中的类型
18 | // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
19 | // 则将该类型上的 ComVisible 特性设置为 true。
20 | [assembly: ComVisible(false)]
21 |
22 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23 | [assembly: Guid("0f13b898-9b63-45d7-99e7-dcf7177e40e6")]
24 |
25 | // 程序集的版本信息由下面四个值组成:
26 | //
27 | // 主版本
28 | // 次版本
29 | // 生成号
30 | // 修订号
31 | //
32 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33 | // 方法是按如下所示使用“*”:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/INIFileTest/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace INIFileTest.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/SerialCommunication/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace SerialCommunication.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/SerialCommunication.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2012
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SerialCommunication", "SerialCommunication\SerialCommunication.csproj", "{0484DB61-BF35-438B-B02A-08243EF3AFA8}"
5 | EndProject
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "INIFileTest", "INIFileTest\INIFileTest.csproj", "{D8AD913A-723B-4BAB-A8E5-A07FB8C26592}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {0484DB61-BF35-438B-B02A-08243EF3AFA8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {0484DB61-BF35-438B-B02A-08243EF3AFA8}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {0484DB61-BF35-438B-B02A-08243EF3AFA8}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {0484DB61-BF35-438B-B02A-08243EF3AFA8}.Release|Any CPU.Build.0 = Release|Any CPU
18 | {D8AD913A-723B-4BAB-A8E5-A07FB8C26592}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {D8AD913A-723B-4BAB-A8E5-A07FB8C26592}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {D8AD913A-723B-4BAB-A8E5-A07FB8C26592}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {D8AD913A-723B-4BAB-A8E5-A07FB8C26592}.Release|Any CPU.Build.0 = Release|Any CPU
22 | EndGlobalSection
23 | GlobalSection(SolutionProperties) = preSolution
24 | HideSolutionNode = FALSE
25 | EndGlobalSection
26 | EndGlobal
27 |
--------------------------------------------------------------------------------
/INIFileTest/Profile.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace INIFILE
8 | {
9 | class Profile
10 | {
11 | public static void LoadProfile()
12 | {
13 | string strPath = AppDomain.CurrentDomain.BaseDirectory;
14 | _file = new IniFile(strPath + "SerialConfig.ini");
15 |
16 | //读数据,下同
17 | G_BAUDRATE = _file.ReadString("CONFIG", "BaudRate", "4800");
18 | G_DATABITS = _file.ReadString("CONFIG", "DataBits", "8");
19 | G_STOP = _file.ReadString("CONFIG", "StopBits", "1");
20 | G_PARITY = _file.ReadString("CONFIG", "Parity", "NONE");
21 |
22 | }
23 |
24 | public static void SaveProfile()
25 | {
26 | string strPath = AppDomain.CurrentDomain.BaseDirectory;
27 | _file = new IniFile(strPath + "Cfg.ini");
28 |
29 | //写数据,下同
30 | _file.WriteString("CONFIG", "BaudRate", G_BAUDRATE);
31 | _file.WriteString("CONFIG", "DataBits", G_DATABITS);
32 | _file.WriteString("CONFIG", "StopBits", G_STOP);
33 | _file.WriteString("CONFIG", "G_PARITY", G_PARITY);
34 | }
35 |
36 | //内置了一个对象
37 | private static IniFile _file;
38 |
39 | //给ini文件赋新值,并且影响界面下拉框的显示
40 | public static string G_BAUDRATE = "1200";
41 | public static string G_DATABITS = "8";
42 | public static string G_STOP = "1";
43 | public static string G_PARITY = "NONE";
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/SerialCommunication/Profile.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace INIFILE
8 | {
9 | class Profile
10 | {
11 | public static void LoadProfile()
12 | {
13 | string strPath = AppDomain.CurrentDomain.BaseDirectory;
14 | _file = new IniFile(strPath + "Cfg.ini");
15 |
16 | //读数据,下同
17 | G_BAUDRATE = _file.ReadString("CONFIG", "BaudRate", "4800");
18 | G_DATABITS = _file.ReadString("CONFIG", "DataBits", "8");
19 | G_STOP = _file.ReadString("CONFIG", "StopBits", "1");
20 | G_PARITY = _file.ReadString("CONFIG", "Parity", "NONE");
21 |
22 | }
23 |
24 | public static void SaveProfile()
25 | {
26 | string strPath = AppDomain.CurrentDomain.BaseDirectory;
27 | _file = new IniFile(strPath + "Cfg.ini");
28 |
29 | //写数据,下同
30 | _file.WriteString("CONFIG", "BaudRate", G_BAUDRATE);
31 | _file.WriteString("CONFIG", "DataBits", G_DATABITS);
32 | _file.WriteString("CONFIG", "StopBits", G_STOP);
33 | _file.WriteString("CONFIG", "G_PARITY", G_PARITY);
34 | }
35 |
36 | //内置了一个对象
37 | private static IniFile _file;
38 |
39 | //给ini文件赋新值,并且影响界面下拉框的显示
40 | public static string G_BAUDRATE = "1200";
41 | public static string G_DATABITS = "8";
42 | public static string G_STOP = "1";
43 | public static string G_PARITY = "NONE";
44 |
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/SerialCommunication/obj/Debug/SerialCommunication.csproj.FileListAbsolute.txt:
--------------------------------------------------------------------------------
1 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\bin\Debug\SerialCommunication.exe.config
2 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\bin\Debug\SerialCommunication.exe
3 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\bin\Debug\SerialCommunication.pdb
4 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.csprojResolveAssemblyReference.cache
5 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.Form1.resources
6 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.Properties.Resources.resources
7 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.csproj.GenerateResource.Cache
8 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.exe
9 | c:\users\admin\documents\visual studio 2012\Projects\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.pdb
10 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\bin\Debug\SerialCommunication.exe.config
11 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.exe
12 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.pdb
13 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\bin\Debug\SerialCommunication.exe
14 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\bin\Debug\SerialCommunication.pdb
15 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.csprojResolveAssemblyReference.cache
16 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.Form1.resources
17 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.Properties.Resources.resources
18 | C:\Users\admin\Desktop\GitHub\SerialCommunication\SerialCommunication\obj\Debug\SerialCommunication.csproj.GenerateResource.Cache
19 |
--------------------------------------------------------------------------------
/INIFileTest/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本: 4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace INIFileTest.Properties
12 | {
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// 返回此类使用的、缓存的 ResourceManager 实例。
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("INIFileTest.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// 为所有资源查找重写当前线程的 CurrentUICulture 属性,
56 | /// 方法是使用此强类型资源类。
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/SerialCommunication/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本: 4.0.30319.42000
5 | //
6 | // 对此文件的更改可能会导致不正确的行为,并且如果
7 | // 重新生成代码,这些更改将丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace SerialCommunication.Properties
12 | {
13 |
14 |
15 | ///
16 | /// 一个强类型的资源类,用于查找本地化的字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// 返回此类使用的、缓存的 ResourceManager 实例。
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SerialCommunication.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// 为所有资源查找重写当前线程的 CurrentUICulture 属性,
56 | /// 方法是使用此强类型资源类。
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/INIFileTest/INIFileTest.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {D8AD913A-723B-4BAB-A8E5-A07FB8C26592}
8 | WinExe
9 | Properties
10 | INIFileTest
11 | INIFileTest
12 | v4.5.1
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | Form
49 |
50 |
51 | Form1.cs
52 |
53 |
54 |
55 |
56 |
57 |
58 | Form1.cs
59 |
60 |
61 | ResXFileCodeGenerator
62 | Resources.Designer.cs
63 | Designer
64 |
65 |
66 | True
67 | Resources.resx
68 |
69 |
70 | SettingsSingleFileGenerator
71 | Settings.Designer.cs
72 |
73 |
74 | True
75 | Settings.settings
76 | True
77 |
78 |
79 |
80 |
81 |
82 |
83 |
90 |
--------------------------------------------------------------------------------
/SerialCommunication/SerialCommunication.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {0484DB61-BF35-438B-B02A-08243EF3AFA8}
8 | WinExe
9 | Properties
10 | SerialCommunication
11 | SerialCommunication
12 | v4.5.1
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | Form
49 |
50 |
51 | Form1.cs
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 | Form1.cs
60 |
61 |
62 | ResXFileCodeGenerator
63 | Resources.Designer.cs
64 | Designer
65 |
66 |
67 | True
68 | Resources.resx
69 |
70 |
71 | SettingsSingleFileGenerator
72 | Settings.Designer.cs
73 |
74 |
75 | True
76 | Settings.settings
77 | True
78 |
79 |
80 |
81 |
82 |
83 |
84 |
91 |
--------------------------------------------------------------------------------
/INIFileTest/Form1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Data;
5 | using System.Drawing;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Runtime.InteropServices;
9 | using System.Text;
10 | using System.Threading.Tasks;
11 | using System.Windows.Forms;
12 |
13 | namespace INIFileTest
14 | {
15 | public partial class Form1 : Form
16 | {
17 |
18 | #region "声明变量"
19 |
20 | ///
21 | /// 写入INI文件
22 | ///
23 | /// 节点名称[如[TypeName]]
24 | /// 键
25 | /// 值
26 | /// 文件路径
27 | ///
28 | [DllImport("kernel32")]
29 | private static extern long WritePrivateProfileString(string section,string key,string val,string filepath);
30 | ///
31 | /// 读取INI文件
32 | ///
33 | /// 节点名称
34 | /// 键
35 | /// 值
36 | /// stringbulider对象
37 | /// 字节大小
38 | /// 文件路径
39 | ///
40 | [DllImport("kernel32")]
41 | private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retval,int size,string filePath);
42 |
43 | private string strFilePath = Application.StartupPath + "\\FileConfig.ini";//获取INI文件路径
44 | private string strSec =""; //INI文件名
45 |
46 | #endregion
47 |
48 |
49 | public Form1()
50 | {
51 | InitializeComponent();
52 | }
53 |
54 | private void Form1_Load(object sender, EventArgs e)
55 | {
56 |
57 | }
58 | ///
59 | /// 写入按钮事件
60 | ///
61 | private void writeBtn_Click(object sender, EventArgs e)
62 | {
63 | try
64 | {
65 | //根据INI文件名设置要写入INI文件的节点名称
66 | //此处的节点名称可以根据实际需要进行配置
67 | strSec = Path.GetFileNameWithoutExtension(strFilePath);
68 | WritePrivateProfileString(strSec, "Name", nameTxt.Text.Trim(), strFilePath);
69 | WritePrivateProfileString(strSec, "Sex", sexTxt.Text.Trim(), strFilePath);
70 | WritePrivateProfileString(strSec, "Age", ageTxt.Text.Trim(), strFilePath);
71 | WritePrivateProfileString(strSec, "Address", addressTxt.Text.Trim(), strFilePath);
72 | MessageBox.Show("写入成功","提示信息",MessageBoxButtons.OK,MessageBoxIcon.Information);
73 | }
74 | catch (Exception ex)
75 | {
76 | MessageBox.Show(ex.ToString());
77 | }
78 | }
79 |
80 | ///
81 | /// 读取按钮事件
82 | ///
83 | private void readBtn_Click(object sender, EventArgs e)
84 | {
85 | if (File.Exists(strFilePath))
86 | {
87 | strSec = Path.GetFileNameWithoutExtension(strFilePath);
88 | nameTxt.Text = ContentValue(strSec,"Name");
89 | sexTxt.Text = ContentValue(strSec, "Sex");
90 | ageTxt.Text = ContentValue(strSec, "Age");
91 | addressTxt.Text = ContentValue(strSec, "Address");
92 | }
93 | else
94 | {
95 | MessageBox.Show("INI文件不存在");
96 | }
97 | }
98 |
99 | ///
100 | /// 读取INI文件中内容方法
101 | ///
102 | ///
103 | ///
104 | ///
105 | private string ContentValue(string Section, string key)
106 | {
107 | StringBuilder temp = new StringBuilder(1024);
108 | GetPrivateProfileString(Section,key,"",temp,1024,strFilePath);
109 | return temp.ToString();
110 | }
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/INIFileTest/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/SerialCommunication/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/INIFileTest/Form1.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
--------------------------------------------------------------------------------
/SerialCommunication/Form1.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | 17, 17
122 |
123 |
124 | 157, 17
125 |
126 |
--------------------------------------------------------------------------------
/INIFileTest/IniFile.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Runtime.InteropServices;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace INIFILE
9 | {
10 | public abstract class CustomIniFile
11 | {
12 | public CustomIniFile(string AFileName)
13 | {
14 | FFileName = AFileName;
15 | }
16 | private string FFileName;
17 | public string FileName
18 | {
19 | get { return FFileName; }
20 | }
21 | public virtual bool SectionExists(string Section)
22 | {
23 | List vStrings = new List();
24 | ReadSections(vStrings);
25 | return vStrings.Contains(Section);
26 | }
27 | public virtual bool ValueExists(string Section, string Ident)
28 | {
29 | List vStrings = new List();
30 | ReadSection(Section, vStrings);
31 | return vStrings.Contains(Ident);
32 | }
33 | public abstract string ReadString(string Section, string Ident, string Default);
34 | public abstract bool WriteString(string Section, string Ident, string Value);
35 | public abstract bool ReadSectionValues(string Section, List Strings);
36 | public abstract bool ReadSection(string Section, List Strings);
37 | public abstract bool ReadSections(List Strings);
38 | public abstract bool EraseSection(string Section);
39 | public abstract bool DeleteKey(string Section, string Ident);
40 | public abstract bool UpdateFile();
41 | }
42 |
43 | public class IniFile : CustomIniFile
44 | {
45 | [DllImport("kernel32")]
46 | private static extern uint GetPrivateProfileString(
47 | string lpAppName, // points to section name
48 | string lpKeyName, // points to key name
49 | string lpDefault, // points to default string
50 | byte[] lpReturnedString, // points to destination buffer
51 | uint nSize, // size of destination buffer
52 | string lpFileName // points to initialization filename
53 | );
54 |
55 | [DllImport("kernel32")]
56 | private static extern bool WritePrivateProfileString(
57 | string lpAppName, // pointer to section name
58 | string lpKeyName, // pointer to key name
59 | string lpString, // pointer to string to add
60 | string lpFileName // pointer to initialization filename
61 | );
62 |
63 | ///
64 | /// 构造IniFile实例。
65 | /// 指定文件名
66 | ///
67 | public IniFile(string AFileName)
68 | : base(AFileName)
69 | {
70 | }
71 |
72 | ///
73 | /// 析够IniFile实例。
74 | ///
75 | ~IniFile()
76 | {
77 | UpdateFile();
78 | }
79 |
80 | ///
81 | /// 读取字符串值。
82 | /// 指定变量标识。
83 | /// 指定所在区域。
84 | /// 指定默认值。
85 | /// 返回读取的字符串。如果读取失败则返回该值。
86 | ///
87 | public override string ReadString(string Section, string Ident, string Default)
88 | {
89 | byte[] vBuffer = new byte[2048];
90 | uint vCount = GetPrivateProfileString(Section,
91 | Ident, Default, vBuffer, (uint)vBuffer.Length, FileName);
92 | return Encoding.Default.GetString(vBuffer, 0, (int)vCount);
93 | }
94 | ///
95 | /// 写入字符串值。
96 | ///
97 | /// 指定所在区域。
98 | /// 指定变量标识。
99 | /// 所要写入的变量值。
100 | /// 返回写入是否成功。
101 | public override bool WriteString(string Section, string Ident, string Value)
102 | {
103 | return WritePrivateProfileString(Section, Ident, Value, FileName);
104 | }
105 |
106 | ///
107 | /// 获得区域的完整文本。(变量名=值格式)。
108 | ///
109 | /// 指定区域标识。
110 | /// 输出处理结果。
111 | /// 返回读取是否成功。
112 | public override bool ReadSectionValues(string Section, List Strings)
113 | {
114 | List vIdentList = new List();
115 | if (!ReadSection(Section, vIdentList)) return false;
116 | foreach (string vIdent in vIdentList)
117 | Strings.Add(string.Format("{0}={1}", vIdent, ReadString(Section, vIdent, "")));
118 | return true;
119 | }
120 |
121 | ///
122 | /// 读取区域变量名列表。
123 | ///
124 | /// 指定区域名。
125 | /// 指定输出列表。
126 | /// 返回获取是否成功。
127 | public override bool ReadSection(string Section, List Strings)
128 | {
129 | byte[] vBuffer = new byte[16384];
130 | uint vLength = GetPrivateProfileString(Section, null, null, vBuffer,
131 | (uint)vBuffer.Length, FileName);
132 | int j = 0;
133 | for (int i = 0; i < vLength; i++)
134 | if (vBuffer[i] == 0)
135 | {
136 | Strings.Add(Encoding.Default.GetString(vBuffer, j, i - j));
137 | j = i + 1;
138 | }
139 | return true;
140 | }
141 |
142 | ///
143 | /// 读取区域名列表。
144 | ///
145 | /// 指定输出列表。
146 | ///
147 | public override bool ReadSections(List Strings)
148 | {
149 | byte[] vBuffer = new byte[16384];
150 | uint vLength = GetPrivateProfileString(null, null, null, vBuffer,
151 | (uint)vBuffer.Length, FileName);
152 | int j = 0;
153 | for (int i = 0; i < vLength; i++)
154 | if (vBuffer[i] == 0)
155 | {
156 | Strings.Add(Encoding.Default.GetString(vBuffer, j, i - j));
157 | j = i + 1;
158 | }
159 | return true;
160 | }
161 |
162 | ///
163 | /// 删除指定区域。
164 | ///
165 | /// 指定区域名。
166 | /// 返回删除是否成功。
167 | public override bool EraseSection(string Section)
168 | {
169 | return WritePrivateProfileString(Section, null, null, FileName);
170 | }
171 |
172 | ///
173 | /// 删除指定变量。
174 | ///
175 | /// 变量所在区域。
176 | /// 变量标识。
177 | /// 返回删除是否成功。
178 | public override bool DeleteKey(string Section, string Ident)
179 | {
180 | return WritePrivateProfileString(Section, Ident, null, FileName);
181 | }
182 |
183 | ///
184 | /// 更新文件。
185 | ///
186 | /// 返回更新是否成功。
187 | public override bool UpdateFile()
188 | {
189 | return WritePrivateProfileString(null, null, null, FileName);
190 | }
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/SerialCommunication/IniFile.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Runtime.InteropServices;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace INIFILE
9 | {
10 | public abstract class CustomIniFile
11 | {
12 | public CustomIniFile(string AFileName)
13 | {
14 | FFileName = AFileName;
15 | }
16 | private string FFileName;
17 | public string FileName
18 | {
19 | get { return FFileName; }
20 | }
21 | public virtual bool SectionExists(string Section)
22 | {
23 | List vStrings = new List();
24 | ReadSections(vStrings);
25 | return vStrings.Contains(Section);
26 | }
27 | public virtual bool ValueExists(string Section, string Ident)
28 | {
29 | List vStrings = new List();
30 | ReadSection(Section, vStrings);
31 | return vStrings.Contains(Ident);
32 | }
33 | public abstract string ReadString(string Section, string Ident, string Default);
34 | public abstract bool WriteString(string Section, string Ident, string Value);
35 | public abstract bool ReadSectionValues(string Section, List Strings);
36 | public abstract bool ReadSection(string Section, List Strings);
37 | public abstract bool ReadSections(List Strings);
38 | public abstract bool EraseSection(string Section);
39 | public abstract bool DeleteKey(string Section, string Ident);
40 | public abstract bool UpdateFile();
41 | }
42 |
43 | public class IniFile : CustomIniFile
44 | {
45 | [DllImport("kernel32")]
46 | private static extern uint GetPrivateProfileString(
47 | string lpAppName, // points to section name
48 | string lpKeyName, // points to key name
49 | string lpDefault, // points to default string
50 | byte[] lpReturnedString, // points to destination buffer
51 | uint nSize, // size of destination buffer
52 | string lpFileName // points to initialization filename
53 | );
54 |
55 | [DllImport("kernel32")]
56 | private static extern bool WritePrivateProfileString(
57 | string lpAppName, // pointer to section name
58 | string lpKeyName, // pointer to key name
59 | string lpString, // pointer to string to add
60 | string lpFileName // pointer to initialization filename
61 | );
62 |
63 | ///
64 | /// 构造IniFile实例。
65 | /// 指定文件名
66 | ///
67 | public IniFile(string AFileName)
68 | : base(AFileName)
69 | {
70 | }
71 |
72 | ///
73 | /// 析够IniFile实例。
74 | ///
75 | ~IniFile()
76 | {
77 | UpdateFile();
78 | }
79 |
80 | ///
81 | /// 读取字符串值。
82 | /// 指定变量标识。
83 | /// 指定所在区域。
84 | /// 指定默认值。
85 | /// 返回读取的字符串。如果读取失败则返回该值。
86 | ///
87 | public override string ReadString(string Section, string Ident, string Default)
88 | {
89 | byte[] vBuffer = new byte[2048];
90 | uint vCount = GetPrivateProfileString(Section,
91 | Ident, Default, vBuffer, (uint)vBuffer.Length, FileName);
92 | return Encoding.Default.GetString(vBuffer, 0, (int)vCount);
93 | }
94 | ///
95 | /// 写入字符串值。
96 | ///
97 | /// 指定所在区域。
98 | /// 指定变量标识。
99 | /// 所要写入的变量值。
100 | /// 返回写入是否成功。
101 | public override bool WriteString(string Section, string Ident, string Value)
102 | {
103 | return WritePrivateProfileString(Section, Ident, Value, FileName);
104 | }
105 |
106 | ///
107 | /// 获得区域的完整文本。(变量名=值格式)。
108 | ///
109 | /// 指定区域标识。
110 | /// 输出处理结果。
111 | /// 返回读取是否成功。
112 | public override bool ReadSectionValues(string Section, List Strings)
113 | {
114 | List vIdentList = new List();
115 | if (!ReadSection(Section, vIdentList)) return false;
116 | foreach (string vIdent in vIdentList)
117 | Strings.Add(string.Format("{0}={1}", vIdent, ReadString(Section, vIdent, "")));
118 | return true;
119 | }
120 |
121 | ///
122 | /// 读取区域变量名列表。
123 | ///
124 | /// 指定区域名。
125 | /// 指定输出列表。
126 | /// 返回获取是否成功。
127 | public override bool ReadSection(string Section, List Strings)
128 | {
129 | byte[] vBuffer = new byte[16384];
130 | uint vLength = GetPrivateProfileString(Section, null, null, vBuffer,
131 | (uint)vBuffer.Length, FileName);
132 | int j = 0;
133 | for (int i = 0; i < vLength; i++)
134 | if (vBuffer[i] == 0)
135 | {
136 | Strings.Add(Encoding.Default.GetString(vBuffer, j, i - j));
137 | j = i + 1;
138 | }
139 | return true;
140 | }
141 |
142 | ///
143 | /// 读取区域名列表。
144 | ///
145 | /// 指定输出列表。
146 | ///
147 | public override bool ReadSections(List Strings)
148 | {
149 | byte[] vBuffer = new byte[16384];
150 | uint vLength = GetPrivateProfileString(null, null, null, vBuffer,
151 | (uint)vBuffer.Length, FileName);
152 | int j = 0;
153 | for (int i = 0; i < vLength; i++)
154 | if (vBuffer[i] == 0)
155 | {
156 | Strings.Add(Encoding.Default.GetString(vBuffer, j, i - j));
157 | j = i + 1;
158 | }
159 | return true;
160 | }
161 |
162 | ///
163 | /// 删除指定区域。
164 | ///
165 | /// 指定区域名。
166 | /// 返回删除是否成功。
167 | public override bool EraseSection(string Section)
168 | {
169 | return WritePrivateProfileString(Section, null, null, FileName);
170 | }
171 |
172 | ///
173 | /// 删除指定变量。
174 | ///
175 | /// 变量所在区域。
176 | /// 变量标识。
177 | /// 返回删除是否成功。
178 | public override bool DeleteKey(string Section, string Ident)
179 | {
180 | return WritePrivateProfileString(Section, Ident, null, FileName);
181 | }
182 |
183 | ///
184 | /// 更新文件。
185 | ///
186 | /// 返回更新是否成功。
187 | public override bool UpdateFile()
188 | {
189 | return WritePrivateProfileString(null, null, null, FileName);
190 | }
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/INIFileTest/Form1.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace INIFileTest
2 | {
3 | partial class Form1
4 | {
5 | ///
6 | /// 必需的设计器变量。
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// 清理所有正在使用的资源。
12 | ///
13 | /// 如果应释放托管资源,为 true;否则为 false。
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows 窗体设计器生成的代码
24 |
25 | ///
26 | /// 设计器支持所需的方法 - 不要
27 | /// 使用代码编辑器修改此方法的内容。
28 | ///
29 | private void InitializeComponent()
30 | {
31 | this.groupBox1 = new System.Windows.Forms.GroupBox();
32 | this.nameLab = new System.Windows.Forms.Label();
33 | this.sexLab = new System.Windows.Forms.Label();
34 | this.ageLab = new System.Windows.Forms.Label();
35 | this.addressLab = new System.Windows.Forms.Label();
36 | this.nameTxt = new System.Windows.Forms.TextBox();
37 | this.sexTxt = new System.Windows.Forms.TextBox();
38 | this.ageTxt = new System.Windows.Forms.TextBox();
39 | this.addressTxt = new System.Windows.Forms.TextBox();
40 | this.writeBtn = new System.Windows.Forms.Button();
41 | this.readBtn = new System.Windows.Forms.Button();
42 | this.groupBox1.SuspendLayout();
43 | this.SuspendLayout();
44 | //
45 | // groupBox1
46 | //
47 | this.groupBox1.Controls.Add(this.addressTxt);
48 | this.groupBox1.Controls.Add(this.ageTxt);
49 | this.groupBox1.Controls.Add(this.sexTxt);
50 | this.groupBox1.Controls.Add(this.nameTxt);
51 | this.groupBox1.Controls.Add(this.addressLab);
52 | this.groupBox1.Controls.Add(this.ageLab);
53 | this.groupBox1.Controls.Add(this.sexLab);
54 | this.groupBox1.Controls.Add(this.nameLab);
55 | this.groupBox1.Location = new System.Drawing.Point(13, 13);
56 | this.groupBox1.Name = "groupBox1";
57 | this.groupBox1.Size = new System.Drawing.Size(367, 235);
58 | this.groupBox1.TabIndex = 0;
59 | this.groupBox1.TabStop = false;
60 | this.groupBox1.Text = "ini示例";
61 | //
62 | // nameLab
63 | //
64 | this.nameLab.AutoSize = true;
65 | this.nameLab.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
66 | this.nameLab.Location = new System.Drawing.Point(7, 42);
67 | this.nameLab.Name = "nameLab";
68 | this.nameLab.Size = new System.Drawing.Size(69, 20);
69 | this.nameLab.TabIndex = 0;
70 | this.nameLab.Text = "姓名:";
71 | //
72 | // sexLab
73 | //
74 | this.sexLab.AutoSize = true;
75 | this.sexLab.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
76 | this.sexLab.Location = new System.Drawing.Point(7, 89);
77 | this.sexLab.Name = "sexLab";
78 | this.sexLab.Size = new System.Drawing.Size(69, 20);
79 | this.sexLab.TabIndex = 1;
80 | this.sexLab.Text = "性别:";
81 | //
82 | // ageLab
83 | //
84 | this.ageLab.AutoSize = true;
85 | this.ageLab.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
86 | this.ageLab.Location = new System.Drawing.Point(7, 134);
87 | this.ageLab.Name = "ageLab";
88 | this.ageLab.Size = new System.Drawing.Size(69, 20);
89 | this.ageLab.TabIndex = 2;
90 | this.ageLab.Text = "年龄:";
91 | //
92 | // addressLab
93 | //
94 | this.addressLab.AutoSize = true;
95 | this.addressLab.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
96 | this.addressLab.Location = new System.Drawing.Point(7, 181);
97 | this.addressLab.Name = "addressLab";
98 | this.addressLab.Size = new System.Drawing.Size(69, 20);
99 | this.addressLab.TabIndex = 3;
100 | this.addressLab.Text = "地址:";
101 | //
102 | // nameTxt
103 | //
104 | this.nameTxt.Location = new System.Drawing.Point(82, 43);
105 | this.nameTxt.Name = "nameTxt";
106 | this.nameTxt.Size = new System.Drawing.Size(225, 25);
107 | this.nameTxt.TabIndex = 4;
108 | //
109 | // sexTxt
110 | //
111 | this.sexTxt.Location = new System.Drawing.Point(82, 90);
112 | this.sexTxt.Name = "sexTxt";
113 | this.sexTxt.Size = new System.Drawing.Size(225, 25);
114 | this.sexTxt.TabIndex = 5;
115 | //
116 | // ageTxt
117 | //
118 | this.ageTxt.Location = new System.Drawing.Point(82, 135);
119 | this.ageTxt.Name = "ageTxt";
120 | this.ageTxt.Size = new System.Drawing.Size(225, 25);
121 | this.ageTxt.TabIndex = 6;
122 | //
123 | // addressTxt
124 | //
125 | this.addressTxt.Location = new System.Drawing.Point(82, 182);
126 | this.addressTxt.Name = "addressTxt";
127 | this.addressTxt.Size = new System.Drawing.Size(225, 25);
128 | this.addressTxt.TabIndex = 7;
129 | //
130 | // writeBtn
131 | //
132 | this.writeBtn.Location = new System.Drawing.Point(24, 254);
133 | this.writeBtn.Name = "writeBtn";
134 | this.writeBtn.Size = new System.Drawing.Size(128, 37);
135 | this.writeBtn.TabIndex = 1;
136 | this.writeBtn.Text = "写入";
137 | this.writeBtn.UseVisualStyleBackColor = true;
138 | this.writeBtn.Click += new System.EventHandler(this.writeBtn_Click);
139 | //
140 | // readBtn
141 | //
142 | this.readBtn.Location = new System.Drawing.Point(192, 254);
143 | this.readBtn.Name = "readBtn";
144 | this.readBtn.Size = new System.Drawing.Size(128, 37);
145 | this.readBtn.TabIndex = 2;
146 | this.readBtn.Text = "读取";
147 | this.readBtn.UseVisualStyleBackColor = true;
148 | this.readBtn.Click += new System.EventHandler(this.readBtn_Click);
149 | //
150 | // Form1
151 | //
152 | this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
153 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
154 | this.ClientSize = new System.Drawing.Size(359, 369);
155 | this.Controls.Add(this.readBtn);
156 | this.Controls.Add(this.writeBtn);
157 | this.Controls.Add(this.groupBox1);
158 | this.Name = "Form1";
159 | this.Text = "ini测试";
160 | this.Load += new System.EventHandler(this.Form1_Load);
161 | this.groupBox1.ResumeLayout(false);
162 | this.groupBox1.PerformLayout();
163 | this.ResumeLayout(false);
164 |
165 | }
166 |
167 | #endregion
168 |
169 | private System.Windows.Forms.GroupBox groupBox1;
170 | private System.Windows.Forms.TextBox addressTxt;
171 | private System.Windows.Forms.TextBox ageTxt;
172 | private System.Windows.Forms.TextBox sexTxt;
173 | private System.Windows.Forms.TextBox nameTxt;
174 | private System.Windows.Forms.Label addressLab;
175 | private System.Windows.Forms.Label ageLab;
176 | private System.Windows.Forms.Label sexLab;
177 | private System.Windows.Forms.Label nameLab;
178 | private System.Windows.Forms.Button writeBtn;
179 | private System.Windows.Forms.Button readBtn;
180 | }
181 | }
182 |
183 |
--------------------------------------------------------------------------------
/SerialCommunication/ModbusCRC16.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Globalization;
3 | using System.Text;
4 |
5 | namespace SerialCommunication
6 | {
7 | class ModbusCRC16
8 | {
9 | const String HEXES = "0123456789ABCDEF";
10 | byte uchCRCHi = (byte)0xFF;
11 | byte uchCRCLo = (byte)0xFF;
12 | private static byte[] auchCRCHi = { 0x00, (byte) 0xC1, (byte) 0x81,
13 | (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
14 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
15 | (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
16 | (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
17 | (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
18 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01,
19 | (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
20 | (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
21 | (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
22 | (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01,
23 | (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0,
24 | (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
25 | (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
26 | (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00,
27 | (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
28 | (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
29 | (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
30 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
31 | (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
32 | (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
33 | (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
34 | (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01,
35 | (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
36 | (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
37 | (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
38 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
39 | (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
40 | (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
41 | (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
42 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x01,
43 | (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1,
44 | (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
45 | (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
46 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
47 | (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
48 | (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
49 | (byte) 0x40, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
50 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
51 | (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
52 | (byte) 0x80, (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
53 | (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40,
54 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
55 | (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00, (byte) 0xC1,
56 | (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80,
57 | (byte) 0x41, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
58 | (byte) 0x00, (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x00,
59 | (byte) 0xC1, (byte) 0x81, (byte) 0x40, (byte) 0x01, (byte) 0xC0,
60 | (byte) 0x80, (byte) 0x41, (byte) 0x00, (byte) 0xC1, (byte) 0x81,
61 | (byte) 0x40, (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41,
62 | (byte) 0x01, (byte) 0xC0, (byte) 0x80, (byte) 0x41, (byte) 0x00,
63 | (byte) 0xC1, (byte) 0x81, (byte) 0x40 };
64 |
65 | private static byte[] auchCRCLo = { (byte) 0x00, (byte) 0xC0, (byte) 0xC1,
66 | (byte) 0x01, (byte) 0xC3, (byte) 0x03, (byte) 0x02, (byte) 0xC2,
67 | (byte) 0xC6, (byte) 0x06, (byte) 0x07, (byte) 0xC7, (byte) 0x05,
68 | (byte) 0xC5, (byte) 0xC4, (byte) 0x04, (byte) 0xCC, (byte) 0x0C,
69 | (byte) 0x0D, (byte) 0xCD, (byte) 0x0F, (byte) 0xCF, (byte) 0xCE,
70 | (byte) 0x0E, (byte) 0x0A, (byte) 0xCA, (byte) 0xCB, (byte) 0x0B,
71 | (byte) 0xC9, (byte) 0x09, (byte) 0x08, (byte) 0xC8, (byte) 0xD8,
72 | (byte) 0x18, (byte) 0x19, (byte) 0xD9, (byte) 0x1B, (byte) 0xDB,
73 | (byte) 0xDA, (byte) 0x1A, (byte) 0x1E, (byte) 0xDE, (byte) 0xDF,
74 | (byte) 0x1F, (byte) 0xDD, (byte) 0x1D, (byte) 0x1C, (byte) 0xDC,
75 | (byte) 0x14, (byte) 0xD4, (byte) 0xD5, (byte) 0x15, (byte) 0xD7,
76 | (byte) 0x17, (byte) 0x16, (byte) 0xD6, (byte) 0xD2, (byte) 0x12,
77 | (byte) 0x13, (byte) 0xD3, (byte) 0x11, (byte) 0xD1, (byte) 0xD0,
78 | (byte) 0x10, (byte) 0xF0, (byte) 0x30, (byte) 0x31, (byte) 0xF1,
79 | (byte) 0x33, (byte) 0xF3, (byte) 0xF2, (byte) 0x32, (byte) 0x36,
80 | (byte) 0xF6, (byte) 0xF7, (byte) 0x37, (byte) 0xF5, (byte) 0x35,
81 | (byte) 0x34, (byte) 0xF4, (byte) 0x3C, (byte) 0xFC, (byte) 0xFD,
82 | (byte) 0x3D, (byte) 0xFF, (byte) 0x3F, (byte) 0x3E, (byte) 0xFE,
83 | (byte) 0xFA, (byte) 0x3A, (byte) 0x3B, (byte) 0xFB, (byte) 0x39,
84 | (byte) 0xF9, (byte) 0xF8, (byte) 0x38, (byte) 0x28, (byte) 0xE8,
85 | (byte) 0xE9, (byte) 0x29, (byte) 0xEB, (byte) 0x2B, (byte) 0x2A,
86 | (byte) 0xEA, (byte) 0xEE, (byte) 0x2E, (byte) 0x2F, (byte) 0xEF,
87 | (byte) 0x2D, (byte) 0xED, (byte) 0xEC, (byte) 0x2C, (byte) 0xE4,
88 | (byte) 0x24, (byte) 0x25, (byte) 0xE5, (byte) 0x27, (byte) 0xE7,
89 | (byte) 0xE6, (byte) 0x26, (byte) 0x22, (byte) 0xE2, (byte) 0xE3,
90 | (byte) 0x23, (byte) 0xE1, (byte) 0x21, (byte) 0x20, (byte) 0xE0,
91 | (byte) 0xA0, (byte) 0x60, (byte) 0x61, (byte) 0xA1, (byte) 0x63,
92 | (byte) 0xA3, (byte) 0xA2, (byte) 0x62, (byte) 0x66, (byte) 0xA6,
93 | (byte) 0xA7, (byte) 0x67, (byte) 0xA5, (byte) 0x65, (byte) 0x64,
94 | (byte) 0xA4, (byte) 0x6C, (byte) 0xAC, (byte) 0xAD, (byte) 0x6D,
95 | (byte) 0xAF, (byte) 0x6F, (byte) 0x6E, (byte) 0xAE, (byte) 0xAA,
96 | (byte) 0x6A, (byte) 0x6B, (byte) 0xAB, (byte) 0x69, (byte) 0xA9,
97 | (byte) 0xA8, (byte) 0x68, (byte) 0x78, (byte) 0xB8, (byte) 0xB9,
98 | (byte) 0x79, (byte) 0xBB, (byte) 0x7B, (byte) 0x7A, (byte) 0xBA,
99 | (byte) 0xBE, (byte) 0x7E, (byte) 0x7F, (byte) 0xBF, (byte) 0x7D,
100 | (byte) 0xBD, (byte) 0xBC, (byte) 0x7C, (byte) 0xB4, (byte) 0x74,
101 | (byte) 0x75, (byte) 0xB5, (byte) 0x77, (byte) 0xB7, (byte) 0xB6,
102 | (byte) 0x76, (byte) 0x72, (byte) 0xB2, (byte) 0xB3, (byte) 0x73,
103 | (byte) 0xB1, (byte) 0x71, (byte) 0x70, (byte) 0xB0, (byte) 0x50,
104 | (byte) 0x90, (byte) 0x91, (byte) 0x51, (byte) 0x93, (byte) 0x53,
105 | (byte) 0x52, (byte) 0x92, (byte) 0x96, (byte) 0x56, (byte) 0x57,
106 | (byte) 0x97, (byte) 0x55, (byte) 0x95, (byte) 0x94, (byte) 0x54,
107 | (byte) 0x9C, (byte) 0x5C, (byte) 0x5D, (byte) 0x9D, (byte) 0x5F,
108 | (byte) 0x9F, (byte) 0x9E, (byte) 0x5E, (byte) 0x5A, (byte) 0x9A,
109 | (byte) 0x9B, (byte) 0x5B, (byte) 0x99, (byte) 0x59, (byte) 0x58,
110 | (byte) 0x98, (byte) 0x88, (byte) 0x48, (byte) 0x49, (byte) 0x89,
111 | (byte) 0x4B, (byte) 0x8B, (byte) 0x8A, (byte) 0x4A, (byte) 0x4E,
112 | (byte) 0x8E, (byte) 0x8F, (byte) 0x4F, (byte) 0x8D, (byte) 0x4D,
113 | (byte) 0x4C, (byte) 0x8C, (byte) 0x44, (byte) 0x84, (byte) 0x85,
114 | (byte) 0x45, (byte) 0x87, (byte) 0x47, (byte) 0x46, (byte) 0x86,
115 | (byte) 0x82, (byte) 0x42, (byte) 0x43, (byte) 0x83, (byte) 0x41,
116 | (byte) 0x81, (byte) 0x80, (byte) 0x40 };
117 |
118 | public int value;
119 |
120 | public ModbusCRC16()
121 | {
122 | value = 0;
123 |
124 | }
125 |
126 | public void update(byte[] puchMsg, int usDataLen)
127 | {
128 |
129 | int uIndex;
130 | for (int i = 0; i < usDataLen; i++)
131 | {
132 | uIndex = (uchCRCHi ^ puchMsg[i]) & 0xff;
133 |
134 | uchCRCHi = (byte)(uchCRCLo ^ auchCRCHi[uIndex]);
135 | uchCRCLo = auchCRCLo[uIndex];
136 | }
137 | value = ((((int)uchCRCHi) << 8 | (((int)uchCRCLo) & 0xff))) & 0xffff;
138 |
139 | return;
140 | }
141 |
142 | public void reset()
143 | {
144 | value = 0;
145 | uchCRCHi = (byte)0xff;
146 | uchCRCLo = (byte)0xff;
147 | }
148 |
149 | public int getValue()
150 | {
151 | return value;
152 | }
153 |
154 | private static byte uniteBytes(byte src0, byte src1)
155 | {
156 |
157 | byte _b0 = byte.Parse(System.Text.Encoding.Default.GetString(new byte[] { src0 }), NumberStyles.HexNumber);
158 |
159 | _b0 = (byte)(_b0 << 4);
160 |
161 | byte _b1 = byte.Parse(System.Text.Encoding.Default.GetString(new byte[] { src1 }), NumberStyles.HexNumber);
162 |
163 | byte ret = (byte)(_b0 ^ _b1);
164 |
165 | return ret;
166 | }
167 |
168 | private static byte[] HexString2Buf(String src)
169 | {
170 | int len = src.Length;
171 | byte[] ret = new byte[len / 2 + 2];
172 |
173 | byte[] tmp = System.Text.Encoding.Default.GetBytes(src);
174 |
175 | for (int i = 0; i < len; i += 2)
176 | {
177 | ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
178 | }
179 | return ret;
180 | }
181 |
182 | //将16进制的字符串转换为带有CRC校验的字节型数组的方法
183 | public static byte[] getSendBuf(String toSend)
184 | {
185 | toSend = toSend.Replace(" ", "");
186 |
187 | byte[] bb = HexString2Buf(toSend);
188 | ModbusCRC16 crc16 = new ModbusCRC16();
189 | crc16.update(bb, bb.Length - 2);
190 | int ri = crc16.getValue();
191 | bb[bb.Length - 1] = (byte)(0xff & ri);
192 | bb[bb.Length - 2] = (byte)((0xff00 & ri) >> 8);
193 | return bb;
194 | }
195 |
196 | public static bool checkBuf(byte[] bb)
197 | {
198 | ModbusCRC16 crc16 = new ModbusCRC16();
199 | crc16.update(bb, bb.Length - 2);
200 | int ri = crc16.getValue();
201 | if (bb[bb.Length - 1] == (byte)(ri & 0xff)
202 | && bb[bb.Length - 2] == (byte)((0xff00 & ri) >> 8))
203 | return true;
204 | return false;
205 | }
206 |
207 | //将字节型数组转换为字符串的方法(暂时没用到)
208 | public static String getBufHexStr(byte[] raw)
209 | {
210 | if (raw == null)
211 | {
212 | return null;
213 | }
214 | StringBuilder hex = new StringBuilder(2 * raw.Length);
215 | foreach (byte b in raw)
216 | {
217 | hex.Append(HEXES[((b & 0xF0) >> 4)])
218 | .Append(HEXES[((b & 0x0F))]);
219 | }
220 | return hex.ToString();
221 | }
222 |
223 | }
224 | }
225 |
--------------------------------------------------------------------------------
/SerialCommunication/Form1.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace SerialCommunication
2 | {
3 | partial class Form1
4 | {
5 | ///
6 | /// 必需的设计器变量。
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// 清理所有正在使用的资源。
12 | ///
13 | /// 如果应释放托管资源,为 true;否则为 false。
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Windows 窗体设计器生成的代码
24 |
25 | ///
26 | /// 设计器支持所需的方法 - 不要
27 | /// 使用代码编辑器修改此方法的内容。
28 | ///
29 | private void InitializeComponent()
30 | {
31 | this.components = new System.ComponentModel.Container();
32 | this.label1 = new System.Windows.Forms.Label();
33 | this.cbSerial = new System.Windows.Forms.ComboBox();
34 | this.btnSwitch = new System.Windows.Forms.Button();
35 | this.btnSave = new System.Windows.Forms.Button();
36 | this.label2 = new System.Windows.Forms.Label();
37 | this.label3 = new System.Windows.Forms.Label();
38 | this.cbBaudRate = new System.Windows.Forms.ComboBox();
39 | this.cbStop = new System.Windows.Forms.ComboBox();
40 | this.label4 = new System.Windows.Forms.Label();
41 | this.label5 = new System.Windows.Forms.Label();
42 | this.cbDataBits = new System.Windows.Forms.ComboBox();
43 | this.cbParity = new System.Windows.Forms.ComboBox();
44 | this.gpbSend = new System.Windows.Forms.GroupBox();
45 | this.rbSendStr = new System.Windows.Forms.RadioButton();
46 | this.rbSend16 = new System.Windows.Forms.RadioButton();
47 | this.gpbReceive = new System.Windows.Forms.GroupBox();
48 | this.rbRcvStr = new System.Windows.Forms.RadioButton();
49 | this.rbRcv16 = new System.Windows.Forms.RadioButton();
50 | this.cbTimeSend = new System.Windows.Forms.CheckBox();
51 | this.label6 = new System.Windows.Forms.Label();
52 | this.txtSecond = new System.Windows.Forms.TextBox();
53 | this.label7 = new System.Windows.Forms.Label();
54 | this.label8 = new System.Windows.Forms.Label();
55 | this.txtSend = new System.Windows.Forms.TextBox();
56 | this.groupBox3 = new System.Windows.Forms.GroupBox();
57 | this.txtRcv = new System.Windows.Forms.RichTextBox();
58 | this.btnClear = new System.Windows.Forms.Button();
59 | this.btnExit = new System.Windows.Forms.Button();
60 | this.btnSend = new System.Windows.Forms.Button();
61 | this.statusStrip1 = new System.Windows.Forms.StatusStrip();
62 | this.tsSpNum = new System.Windows.Forms.ToolStripStatusLabel();
63 | this.tsBaudRate = new System.Windows.Forms.ToolStripStatusLabel();
64 | this.tsDataBits = new System.Windows.Forms.ToolStripStatusLabel();
65 | this.tsStopBits = new System.Windows.Forms.ToolStripStatusLabel();
66 | this.tsParity = new System.Windows.Forms.ToolStripStatusLabel();
67 | this.timeSend = new System.Windows.Forms.Timer(this.components);
68 | this.cbSendHex = new System.Windows.Forms.CheckBox();
69 | this.txtStrTo16 = new System.Windows.Forms.TextBox();
70 | this.btnSendCRC = new System.Windows.Forms.Button();
71 | this.gpbSend.SuspendLayout();
72 | this.gpbReceive.SuspendLayout();
73 | this.groupBox3.SuspendLayout();
74 | this.statusStrip1.SuspendLayout();
75 | this.SuspendLayout();
76 | //
77 | // label1
78 | //
79 | this.label1.AutoSize = true;
80 | this.label1.Location = new System.Drawing.Point(20, 21);
81 | this.label1.Name = "label1";
82 | this.label1.Size = new System.Drawing.Size(52, 15);
83 | this.label1.TabIndex = 0;
84 | this.label1.Text = "串口:";
85 | //
86 | // cbSerial
87 | //
88 | this.cbSerial.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
89 | this.cbSerial.FormattingEnabled = true;
90 | this.cbSerial.Location = new System.Drawing.Point(83, 18);
91 | this.cbSerial.Name = "cbSerial";
92 | this.cbSerial.Size = new System.Drawing.Size(136, 23);
93 | this.cbSerial.TabIndex = 1;
94 | //
95 | // btnSwitch
96 | //
97 | this.btnSwitch.Location = new System.Drawing.Point(247, 12);
98 | this.btnSwitch.Name = "btnSwitch";
99 | this.btnSwitch.Size = new System.Drawing.Size(127, 32);
100 | this.btnSwitch.TabIndex = 2;
101 | this.btnSwitch.Text = "打开串口";
102 | this.btnSwitch.UseVisualStyleBackColor = true;
103 | this.btnSwitch.Click += new System.EventHandler(this.btnSwitch_Click);
104 | //
105 | // btnSave
106 | //
107 | this.btnSave.Location = new System.Drawing.Point(392, 12);
108 | this.btnSave.Name = "btnSave";
109 | this.btnSave.Size = new System.Drawing.Size(127, 32);
110 | this.btnSave.TabIndex = 3;
111 | this.btnSave.Text = "保存设置";
112 | this.btnSave.UseVisualStyleBackColor = true;
113 | this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
114 | //
115 | // label2
116 | //
117 | this.label2.AutoSize = true;
118 | this.label2.Location = new System.Drawing.Point(20, 73);
119 | this.label2.Name = "label2";
120 | this.label2.Size = new System.Drawing.Size(67, 15);
121 | this.label2.TabIndex = 4;
122 | this.label2.Text = "波特率:";
123 | //
124 | // label3
125 | //
126 | this.label3.AutoSize = true;
127 | this.label3.Location = new System.Drawing.Point(20, 112);
128 | this.label3.Name = "label3";
129 | this.label3.Size = new System.Drawing.Size(67, 15);
130 | this.label3.TabIndex = 5;
131 | this.label3.Text = "停止位:";
132 | //
133 | // cbBaudRate
134 | //
135 | this.cbBaudRate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
136 | this.cbBaudRate.FormattingEnabled = true;
137 | this.cbBaudRate.Items.AddRange(new object[] {
138 | "300",
139 | "600",
140 | "1200",
141 | "2400",
142 | "4800",
143 | "9600",
144 | "19200",
145 | "38400",
146 | "115200"});
147 | this.cbBaudRate.Location = new System.Drawing.Point(86, 70);
148 | this.cbBaudRate.Name = "cbBaudRate";
149 | this.cbBaudRate.Size = new System.Drawing.Size(132, 23);
150 | this.cbBaudRate.TabIndex = 6;
151 | //
152 | // cbStop
153 | //
154 | this.cbStop.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
155 | this.cbStop.FormattingEnabled = true;
156 | this.cbStop.Items.AddRange(new object[] {
157 | "1",
158 | "1.5",
159 | "2"});
160 | this.cbStop.Location = new System.Drawing.Point(86, 112);
161 | this.cbStop.Name = "cbStop";
162 | this.cbStop.Size = new System.Drawing.Size(132, 23);
163 | this.cbStop.TabIndex = 7;
164 | //
165 | // label4
166 | //
167 | this.label4.AutoSize = true;
168 | this.label4.Location = new System.Drawing.Point(282, 73);
169 | this.label4.Name = "label4";
170 | this.label4.Size = new System.Drawing.Size(67, 15);
171 | this.label4.TabIndex = 8;
172 | this.label4.Text = "数据位:";
173 | //
174 | // label5
175 | //
176 | this.label5.AutoSize = true;
177 | this.label5.Location = new System.Drawing.Point(282, 117);
178 | this.label5.Name = "label5";
179 | this.label5.Size = new System.Drawing.Size(67, 15);
180 | this.label5.TabIndex = 9;
181 | this.label5.Text = "校验位:";
182 | //
183 | // cbDataBits
184 | //
185 | this.cbDataBits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
186 | this.cbDataBits.FormattingEnabled = true;
187 | this.cbDataBits.Items.AddRange(new object[] {
188 | "5",
189 | "6",
190 | "7",
191 | "8"});
192 | this.cbDataBits.Location = new System.Drawing.Point(364, 70);
193 | this.cbDataBits.Name = "cbDataBits";
194 | this.cbDataBits.Size = new System.Drawing.Size(132, 23);
195 | this.cbDataBits.TabIndex = 10;
196 | //
197 | // cbParity
198 | //
199 | this.cbParity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
200 | this.cbParity.FormattingEnabled = true;
201 | this.cbParity.Items.AddRange(new object[] {
202 | "无",
203 | "奇校验",
204 | "偶校验"});
205 | this.cbParity.Location = new System.Drawing.Point(364, 113);
206 | this.cbParity.Name = "cbParity";
207 | this.cbParity.Size = new System.Drawing.Size(132, 23);
208 | this.cbParity.TabIndex = 11;
209 | //
210 | // gpbSend
211 | //
212 | this.gpbSend.Controls.Add(this.rbSendStr);
213 | this.gpbSend.Controls.Add(this.rbSend16);
214 | this.gpbSend.Location = new System.Drawing.Point(23, 155);
215 | this.gpbSend.Name = "gpbSend";
216 | this.gpbSend.Size = new System.Drawing.Size(181, 51);
217 | this.gpbSend.TabIndex = 12;
218 | this.gpbSend.TabStop = false;
219 | this.gpbSend.Text = "发送数据格式";
220 | //
221 | // rbSendStr
222 | //
223 | this.rbSendStr.AutoSize = true;
224 | this.rbSendStr.Location = new System.Drawing.Point(102, 26);
225 | this.rbSendStr.Name = "rbSendStr";
226 | this.rbSendStr.Size = new System.Drawing.Size(73, 19);
227 | this.rbSendStr.TabIndex = 1;
228 | this.rbSendStr.TabStop = true;
229 | this.rbSendStr.Text = "字符串";
230 | this.rbSendStr.UseVisualStyleBackColor = true;
231 | //
232 | // rbSend16
233 | //
234 | this.rbSend16.AutoSize = true;
235 | this.rbSend16.Location = new System.Drawing.Point(8, 26);
236 | this.rbSend16.Name = "rbSend16";
237 | this.rbSend16.Size = new System.Drawing.Size(74, 19);
238 | this.rbSend16.TabIndex = 0;
239 | this.rbSend16.TabStop = true;
240 | this.rbSend16.Text = "16进制";
241 | this.rbSend16.UseVisualStyleBackColor = true;
242 | this.rbSend16.CheckedChanged += new System.EventHandler(this.rbSend16_CheckedChanged);
243 | //
244 | // gpbReceive
245 | //
246 | this.gpbReceive.Controls.Add(this.rbRcvStr);
247 | this.gpbReceive.Controls.Add(this.rbRcv16);
248 | this.gpbReceive.Location = new System.Drawing.Point(247, 155);
249 | this.gpbReceive.Name = "gpbReceive";
250 | this.gpbReceive.Size = new System.Drawing.Size(181, 51);
251 | this.gpbReceive.TabIndex = 13;
252 | this.gpbReceive.TabStop = false;
253 | this.gpbReceive.Text = "接收数据格式";
254 | //
255 | // rbRcvStr
256 | //
257 | this.rbRcvStr.AutoSize = true;
258 | this.rbRcvStr.Location = new System.Drawing.Point(102, 26);
259 | this.rbRcvStr.Name = "rbRcvStr";
260 | this.rbRcvStr.Size = new System.Drawing.Size(73, 19);
261 | this.rbRcvStr.TabIndex = 1;
262 | this.rbRcvStr.TabStop = true;
263 | this.rbRcvStr.Text = "字符串";
264 | this.rbRcvStr.UseVisualStyleBackColor = true;
265 | //
266 | // rbRcv16
267 | //
268 | this.rbRcv16.AutoSize = true;
269 | this.rbRcv16.Location = new System.Drawing.Point(8, 26);
270 | this.rbRcv16.Name = "rbRcv16";
271 | this.rbRcv16.Size = new System.Drawing.Size(74, 19);
272 | this.rbRcv16.TabIndex = 0;
273 | this.rbRcv16.TabStop = true;
274 | this.rbRcv16.Text = "16进制";
275 | this.rbRcv16.UseVisualStyleBackColor = true;
276 | //
277 | // cbTimeSend
278 | //
279 | this.cbTimeSend.AutoSize = true;
280 | this.cbTimeSend.Location = new System.Drawing.Point(23, 230);
281 | this.cbTimeSend.Name = "cbTimeSend";
282 | this.cbTimeSend.Size = new System.Drawing.Size(119, 19);
283 | this.cbTimeSend.TabIndex = 14;
284 | this.cbTimeSend.Text = "定时发送数据";
285 | this.cbTimeSend.UseVisualStyleBackColor = true;
286 | //
287 | // label6
288 | //
289 | this.label6.AutoSize = true;
290 | this.label6.Location = new System.Drawing.Point(244, 234);
291 | this.label6.Name = "label6";
292 | this.label6.Size = new System.Drawing.Size(82, 15);
293 | this.label6.TabIndex = 15;
294 | this.label6.Text = "时间间隔:";
295 | //
296 | // txtSecond
297 | //
298 | this.txtSecond.Location = new System.Drawing.Point(332, 228);
299 | this.txtSecond.Name = "txtSecond";
300 | this.txtSecond.Size = new System.Drawing.Size(100, 25);
301 | this.txtSecond.TabIndex = 16;
302 | this.txtSecond.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSecond_KeyPress);
303 | //
304 | // label7
305 | //
306 | this.label7.AutoSize = true;
307 | this.label7.Location = new System.Drawing.Point(438, 234);
308 | this.label7.Name = "label7";
309 | this.label7.Size = new System.Drawing.Size(22, 15);
310 | this.label7.TabIndex = 17;
311 | this.label7.Text = "秒";
312 | //
313 | // label8
314 | //
315 | this.label8.AutoSize = true;
316 | this.label8.Location = new System.Drawing.Point(20, 268);
317 | this.label8.Name = "label8";
318 | this.label8.Size = new System.Drawing.Size(82, 15);
319 | this.label8.TabIndex = 18;
320 | this.label8.Text = "发送数据:";
321 | //
322 | // txtSend
323 | //
324 | this.txtSend.Location = new System.Drawing.Point(23, 287);
325 | this.txtSend.Name = "txtSend";
326 | this.txtSend.Size = new System.Drawing.Size(496, 25);
327 | this.txtSend.TabIndex = 19;
328 | this.txtSend.TextChanged += new System.EventHandler(this.txtSend_TextChanged);
329 | this.txtSend.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSend_KeyPress);
330 | //
331 | // groupBox3
332 | //
333 | this.groupBox3.Controls.Add(this.txtRcv);
334 | this.groupBox3.Location = new System.Drawing.Point(547, 12);
335 | this.groupBox3.Name = "groupBox3";
336 | this.groupBox3.Size = new System.Drawing.Size(451, 328);
337 | this.groupBox3.TabIndex = 20;
338 | this.groupBox3.TabStop = false;
339 | this.groupBox3.Text = "接收方";
340 | //
341 | // txtRcv
342 | //
343 | this.txtRcv.Location = new System.Drawing.Point(0, 25);
344 | this.txtRcv.Name = "txtRcv";
345 | this.txtRcv.Size = new System.Drawing.Size(445, 297);
346 | this.txtRcv.TabIndex = 0;
347 | this.txtRcv.Text = "";
348 | //
349 | // btnClear
350 | //
351 | this.btnClear.Location = new System.Drawing.Point(789, 367);
352 | this.btnClear.Name = "btnClear";
353 | this.btnClear.Size = new System.Drawing.Size(90, 30);
354 | this.btnClear.TabIndex = 21;
355 | this.btnClear.Text = "清空";
356 | this.btnClear.UseVisualStyleBackColor = true;
357 | this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
358 | //
359 | // btnExit
360 | //
361 | this.btnExit.Location = new System.Drawing.Point(908, 367);
362 | this.btnExit.Name = "btnExit";
363 | this.btnExit.Size = new System.Drawing.Size(90, 30);
364 | this.btnExit.TabIndex = 22;
365 | this.btnExit.Text = "退出";
366 | this.btnExit.UseVisualStyleBackColor = true;
367 | this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
368 | //
369 | // btnSend
370 | //
371 | this.btnSend.Location = new System.Drawing.Point(429, 323);
372 | this.btnSend.Name = "btnSend";
373 | this.btnSend.Size = new System.Drawing.Size(90, 30);
374 | this.btnSend.TabIndex = 23;
375 | this.btnSend.Text = "发送";
376 | this.btnSend.UseVisualStyleBackColor = true;
377 | this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
378 | //
379 | // statusStrip1
380 | //
381 | this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
382 | this.tsSpNum,
383 | this.tsBaudRate,
384 | this.tsDataBits,
385 | this.tsStopBits,
386 | this.tsParity});
387 | this.statusStrip1.Location = new System.Drawing.Point(0, 427);
388 | this.statusStrip1.Name = "statusStrip1";
389 | this.statusStrip1.Size = new System.Drawing.Size(1024, 22);
390 | this.statusStrip1.TabIndex = 24;
391 | this.statusStrip1.Text = "statusStrip1";
392 | //
393 | // tsSpNum
394 | //
395 | this.tsSpNum.Name = "tsSpNum";
396 | this.tsSpNum.Size = new System.Drawing.Size(0, 17);
397 | //
398 | // tsBaudRate
399 | //
400 | this.tsBaudRate.Name = "tsBaudRate";
401 | this.tsBaudRate.Size = new System.Drawing.Size(0, 17);
402 | //
403 | // tsDataBits
404 | //
405 | this.tsDataBits.Name = "tsDataBits";
406 | this.tsDataBits.Size = new System.Drawing.Size(0, 17);
407 | //
408 | // tsStopBits
409 | //
410 | this.tsStopBits.Name = "tsStopBits";
411 | this.tsStopBits.Size = new System.Drawing.Size(0, 17);
412 | //
413 | // tsParity
414 | //
415 | this.tsParity.Name = "tsParity";
416 | this.tsParity.Size = new System.Drawing.Size(0, 17);
417 | //
418 | // timeSend
419 | //
420 | this.timeSend.Tick += new System.EventHandler(this.timeSend_Tick);
421 | //
422 | // cbSendHex
423 | //
424 | this.cbSendHex.AutoSize = true;
425 | this.cbSendHex.Location = new System.Drawing.Point(23, 330);
426 | this.cbSendHex.Name = "cbSendHex";
427 | this.cbSendHex.Size = new System.Drawing.Size(180, 19);
428 | this.cbSendHex.TabIndex = 25;
429 | this.cbSendHex.Text = "显示此字符串的16进制";
430 | this.cbSendHex.UseVisualStyleBackColor = true;
431 | this.cbSendHex.CheckedChanged += new System.EventHandler(this.cbSendHex_CheckedChanged);
432 | //
433 | // txtStrTo16
434 | //
435 | this.txtStrTo16.Location = new System.Drawing.Point(23, 367);
436 | this.txtStrTo16.Name = "txtStrTo16";
437 | this.txtStrTo16.ReadOnly = true;
438 | this.txtStrTo16.Size = new System.Drawing.Size(496, 25);
439 | this.txtStrTo16.TabIndex = 26;
440 | //
441 | // btnSendCRC
442 | //
443 | this.btnSendCRC.Location = new System.Drawing.Point(255, 323);
444 | this.btnSendCRC.Name = "btnSendCRC";
445 | this.btnSendCRC.Size = new System.Drawing.Size(144, 30);
446 | this.btnSendCRC.TabIndex = 27;
447 | this.btnSendCRC.Text = "添加CRC校验发送";
448 | this.btnSendCRC.UseVisualStyleBackColor = true;
449 | this.btnSendCRC.Click += new System.EventHandler(this.btnSendCRC_Click);
450 | //
451 | // Form1
452 | //
453 | this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
454 | this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
455 | this.ClientSize = new System.Drawing.Size(1024, 449);
456 | this.Controls.Add(this.btnSendCRC);
457 | this.Controls.Add(this.txtStrTo16);
458 | this.Controls.Add(this.cbSendHex);
459 | this.Controls.Add(this.statusStrip1);
460 | this.Controls.Add(this.btnSend);
461 | this.Controls.Add(this.btnExit);
462 | this.Controls.Add(this.btnClear);
463 | this.Controls.Add(this.groupBox3);
464 | this.Controls.Add(this.txtSend);
465 | this.Controls.Add(this.label8);
466 | this.Controls.Add(this.label7);
467 | this.Controls.Add(this.txtSecond);
468 | this.Controls.Add(this.label6);
469 | this.Controls.Add(this.cbTimeSend);
470 | this.Controls.Add(this.gpbReceive);
471 | this.Controls.Add(this.gpbSend);
472 | this.Controls.Add(this.cbParity);
473 | this.Controls.Add(this.cbDataBits);
474 | this.Controls.Add(this.label5);
475 | this.Controls.Add(this.label4);
476 | this.Controls.Add(this.cbStop);
477 | this.Controls.Add(this.cbBaudRate);
478 | this.Controls.Add(this.label3);
479 | this.Controls.Add(this.label2);
480 | this.Controls.Add(this.btnSave);
481 | this.Controls.Add(this.btnSwitch);
482 | this.Controls.Add(this.cbSerial);
483 | this.Controls.Add(this.label1);
484 | this.Name = "Form1";
485 | this.Text = "串口通信工具1.0";
486 | this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
487 | this.Load += new System.EventHandler(this.Form1_Load);
488 | this.gpbSend.ResumeLayout(false);
489 | this.gpbSend.PerformLayout();
490 | this.gpbReceive.ResumeLayout(false);
491 | this.gpbReceive.PerformLayout();
492 | this.groupBox3.ResumeLayout(false);
493 | this.statusStrip1.ResumeLayout(false);
494 | this.statusStrip1.PerformLayout();
495 | this.ResumeLayout(false);
496 | this.PerformLayout();
497 |
498 | }
499 |
500 | #endregion
501 |
502 | private System.Windows.Forms.Label label1;
503 | private System.Windows.Forms.ComboBox cbSerial;
504 | private System.Windows.Forms.Button btnSwitch;
505 | private System.Windows.Forms.Button btnSave;
506 | private System.Windows.Forms.Label label2;
507 | private System.Windows.Forms.Label label3;
508 | private System.Windows.Forms.ComboBox cbBaudRate;
509 | private System.Windows.Forms.ComboBox cbStop;
510 | private System.Windows.Forms.Label label4;
511 | private System.Windows.Forms.Label label5;
512 | private System.Windows.Forms.ComboBox cbDataBits;
513 | private System.Windows.Forms.ComboBox cbParity;
514 | private System.Windows.Forms.GroupBox gpbSend;
515 | private System.Windows.Forms.RadioButton rbSendStr;
516 | private System.Windows.Forms.RadioButton rbSend16;
517 | private System.Windows.Forms.GroupBox gpbReceive;
518 | private System.Windows.Forms.RadioButton rbRcvStr;
519 | private System.Windows.Forms.RadioButton rbRcv16;
520 | private System.Windows.Forms.CheckBox cbTimeSend;
521 | private System.Windows.Forms.Label label6;
522 | private System.Windows.Forms.TextBox txtSecond;
523 | private System.Windows.Forms.Label label7;
524 | private System.Windows.Forms.Label label8;
525 | private System.Windows.Forms.TextBox txtSend;
526 | private System.Windows.Forms.GroupBox groupBox3;
527 | private System.Windows.Forms.Button btnClear;
528 | private System.Windows.Forms.Button btnExit;
529 | private System.Windows.Forms.Button btnSend;
530 | private System.Windows.Forms.StatusStrip statusStrip1;
531 | private System.Windows.Forms.ToolStripStatusLabel tsSpNum;
532 | private System.Windows.Forms.ToolStripStatusLabel tsBaudRate;
533 | private System.Windows.Forms.ToolStripStatusLabel tsDataBits;
534 | private System.Windows.Forms.ToolStripStatusLabel tsStopBits;
535 | private System.Windows.Forms.ToolStripStatusLabel tsParity;
536 | private System.Windows.Forms.Timer timeSend;
537 | private System.Windows.Forms.RichTextBox txtRcv;
538 | private System.Windows.Forms.CheckBox cbSendHex;
539 | private System.Windows.Forms.TextBox txtStrTo16;
540 | private System.Windows.Forms.Button btnSendCRC;
541 | }
542 | }
543 |
544 |
--------------------------------------------------------------------------------
/SerialCommunication/Form1.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Data;
5 | using System.Drawing;
6 | using System.IO.Ports;
7 | using System.Linq;
8 | using System.Text;
9 | using System.Threading.Tasks;
10 | using System.Windows.Forms;
11 | using System.Runtime.InteropServices;
12 | using INIFILE;
13 | using System.Text.RegularExpressions;
14 |
15 | namespace SerialCommunication
16 | {
17 | public partial class Form1 : Form
18 | {
19 | #region 日志记录,在richtextbox中显示不同颜色文字的方法
20 |
21 | public delegate void LogAppendDelegate(Color color, string text);
22 |
23 | //追加显示文本
24 | public void LogAppend(Color color, string msg)
25 | {
26 | txtRcv.SelectionColor = color;
27 | txtRcv.AppendText(msg);
28 | txtRcv.AppendText("\n");
29 | }
30 |
31 | //显示错误信息
32 | public void LogError(string msg)
33 | {
34 | LogAppendDelegate lad = new LogAppendDelegate(LogAppend);
35 | txtRcv.Invoke(lad,Color.Red,DateTime.Now.ToString("HH:mm:ss ")+msg);
36 | }
37 |
38 | //显示警告信息
39 | public void LogWarning(string msg)
40 | {
41 | LogAppendDelegate lad = new LogAppendDelegate(LogAppend);
42 | txtRcv.Invoke(lad,Color.Violet,DateTime.Now.ToString("HH:mm:ss ")+msg);
43 | }
44 |
45 | //显示信息
46 | public void LogMessage(string msg)
47 | {
48 | LogAppendDelegate lad = new LogAppendDelegate(LogAppend);
49 | txtRcv.Invoke(lad,Color.Black,DateTime.Now.ToString("HH:mm:ss ")+msg);
50 | }
51 | //发送信息的设置
52 | public void SendMessage(string msg)
53 | {
54 | LogAppendDelegate lad = new LogAppendDelegate(LogAppend);
55 | txtRcv.Invoke(lad, Color.Green, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + msg);
56 | }
57 | //接收信息的设置
58 | public void RcvMessage(string msg)
59 | {
60 | LogAppendDelegate lad = new LogAppendDelegate(LogAppend);
61 | txtRcv.Invoke(lad, Color.Blue, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + msg);
62 | }
63 | #endregion
64 |
65 | SerialPort serialPort = new SerialPort();
66 |
67 | public Form1()
68 | {
69 | InitializeComponent();
70 | }
71 |
72 | #region Form_load 窗口加载
73 | //窗口加载
74 | private void Form1_Load(object sender, EventArgs e)
75 | {
76 | //加载所有
77 | INIFILE.Profile.LoadProfile();
78 |
79 | // 预置波特率
80 | switch (Profile.G_BAUDRATE)
81 | {
82 | case "300":
83 | cbBaudRate.SelectedIndex = 0;
84 | break;
85 | case "600":
86 | cbBaudRate.SelectedIndex = 1;
87 | break;
88 | case "1200":
89 | cbBaudRate.SelectedIndex = 2;
90 | break;
91 | case "2400":
92 | cbBaudRate.SelectedIndex = 3;
93 | break;
94 | case "4800":
95 | cbBaudRate.SelectedIndex = 4;
96 | break;
97 | case "9600":
98 | cbBaudRate.SelectedIndex = 5;
99 | break;
100 | case "19200":
101 | cbBaudRate.SelectedIndex = 6;
102 | break;
103 | case "38400":
104 | cbBaudRate.SelectedIndex = 7;
105 | break;
106 | case "115200":
107 | cbBaudRate.SelectedIndex = 8;
108 | break;
109 | default:
110 | {
111 | MessageBox.Show("波特率预置参数错误。", "异常提示信息",
112 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
113 | return;
114 | }
115 | }
116 |
117 | //预置波特率
118 | switch (Profile.G_DATABITS)
119 | {
120 | case "5":
121 | cbDataBits.SelectedIndex = 0;
122 | break;
123 | case "6":
124 | cbDataBits.SelectedIndex = 1;
125 | break;
126 | case "7":
127 | cbDataBits.SelectedIndex = 2;
128 | break;
129 | case "8":
130 | cbDataBits.SelectedIndex = 3;
131 | break;
132 | default:
133 | {
134 | MessageBox.Show("数据位预置参数错误。", "异常提示信息",
135 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
136 | return;
137 | }
138 |
139 | }
140 | //预置停止位
141 | switch (Profile.G_STOP)
142 | {
143 | case "1":
144 | cbStop.SelectedIndex = 0;
145 | break;
146 | case "1.5":
147 | cbStop.SelectedIndex = 1;
148 | break;
149 | case "2":
150 | cbStop.SelectedIndex = 2;
151 | break;
152 | default:
153 | {
154 | MessageBox.Show("停止位预置参数错误。", "异常提示信息",
155 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
156 | return;
157 | }
158 | }
159 |
160 | //预置校验位
161 | switch (Profile.G_PARITY)
162 | {
163 | case "NONE":
164 | cbParity.SelectedIndex = 0;
165 | break;
166 | case "ODD":
167 | cbParity.SelectedIndex = 1;
168 | break;
169 | case "EVEN":
170 | cbParity.SelectedIndex = 2;
171 | break;
172 | default:
173 | {
174 | MessageBox.Show("校验位预置参数错误。","异常提示信息",
175 | MessageBoxButtons.OK,MessageBoxIcon.Warning);
176 | return;
177 | }
178 | }
179 |
180 | //检查是否含有串口
181 | string[] str = SerialPort.GetPortNames();
182 | if (str == null)
183 | {
184 | MessageBox.Show("本机没有串口!", "信息提示",
185 | MessageBoxButtons.OK,MessageBoxIcon.Information);
186 | return;
187 | }
188 |
189 | //添加串口项目
190 | foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
191 | {
192 | //获取有多少个COM口
193 | cbSerial.Items.Add(s);
194 | }
195 |
196 | //串口设置默认选择项
197 | //设置cbSerial的默认选项
198 | cbSerial.SelectedIndex = 0;
199 | serialPort.BaudRate = 9600;
200 |
201 | //这个类中不检查跨线程的调用是否合法
202 | /*.NET2.0以后加强了安全机制,不允许在WinForm中直接跨线程访问控件的属性*/
203 | Control.CheckForIllegalCrossThreadCalls = false;
204 |
205 | serialPort.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived);
206 |
207 | //发送和接收格式默认是字符串
208 |
209 | //rbSend16.Checked = true;
210 | //rbRcv16.Checked = true;
211 |
212 | rbSendStr.Checked = true;
213 | rbRcvStr.Checked = true;
214 | btnSendCRC.Enabled = false;
215 |
216 | //设置数据读取超时为1秒
217 | serialPort.ReadTimeout = 1000;
218 |
219 | //设置编码
220 | //serialPort.Encoding = System.Text.Encoding.GetEncoding("UTF-8");
221 |
222 | //关闭串口
223 | serialPort.Close();
224 | }
225 | #endregion
226 |
227 | #region sp1_DataReceived 处理接收数据
228 | ///
229 | /// 对接收的数据进行处理的方法
230 | ///
231 | void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
232 | {
233 | if (serialPort.IsOpen)
234 | {
235 | //BytestoRead:sp1接收的字符个数
236 | byte[] receiveBytes = new byte[serialPort.BytesToRead];
237 | serialPort.Read(receiveBytes, 0, receiveBytes.Length);
238 | serialPort.DiscardInBuffer();
239 |
240 | //rdRcvStr:"接收字符串"单选按钮
241 | if (rbRcvStr.Checked)
242 | {
243 | string receiveStr = ByteToString(receiveBytes);
244 | RcvMessage(receiveStr);
245 | }
246 | else
247 | {
248 | try
249 | {
250 | string strRcv = ByteToHex(receiveBytes);
251 | RcvMessage(strRcv);
252 | }
253 | catch (Exception ex)
254 | {
255 | MessageBox.Show(ex.Message,"异常提示信息",
256 | MessageBoxButtons.OK,MessageBoxIcon.Warning);
257 | txtSend.Text = "";
258 | }
259 | }
260 | }
261 | else
262 | {
263 | MessageBox.Show("请打开某个串口", "信息提示",
264 | MessageBoxButtons.OK,MessageBoxIcon.Information);
265 | }
266 | }
267 |
268 | #endregion
269 |
270 | #region btnClear_Click 清空按钮
271 | ///
272 | /// "清空"按钮事件
273 | ///
274 | private void btnClear_Click(object sender, EventArgs e)
275 | {
276 | txtRcv.Text = "";
277 | }
278 | #endregion
279 |
280 | #region btnExit_Click 退出按钮
281 | ///
282 | /// "退出"按钮事件
283 | ///
284 | private void btnExit_Click(object sender, EventArgs e)
285 | {
286 | Application.Exit();
287 | }
288 | #endregion
289 |
290 | #region btnSend_Click 发送按钮:处理发送数据
291 | ///
292 | /// 点击“发送按钮”事件
293 | ///
294 | private void btnSend_Click(object sender, EventArgs e)
295 | {
296 | //发送前判断串口是否打开
297 | if (!serialPort.IsOpen)
298 | {
299 | MessageBox.Show("请先打开串口!","提示信息",
300 | MessageBoxButtons.OK,MessageBoxIcon.Information);
301 | return;
302 | }
303 | //判断cbTimeSend是否被勾选,来决定是否启动Timer控件进行定时发送
304 | if (cbTimeSend.Checked)
305 | {
306 | timeSend.Enabled = true;
307 | }
308 | else
309 | {
310 | timeSend.Enabled = false;
311 | }
312 |
313 | string strSend = txtSend.Text;
314 |
315 | if (rbSend16.Checked==true)
316 | {
317 | try
318 | {
319 | //如果以16进制形式发送,将16进制数转换为byte数组进行发送
320 | byte[] byteBuffer = HexToByte(strSend);
321 | serialPort.Write(byteBuffer, 0, byteBuffer.Length);
322 | SendMessage(ByteToHex(byteBuffer));
323 | }
324 | catch (Exception ex)
325 | {
326 | MessageBox.Show("16进制数的格式或长度不正确,请检查格式后重新发送。","信息提示",
327 | MessageBoxButtons.OK,MessageBoxIcon.Information);
328 | }
329 |
330 | }
331 | else if(rbSendStr.Checked==true)
332 | {
333 | //如果以字符串形式发送,将字符串转换为byte数组进行发送
334 | byte[] byteBuffer = StringToByte(txtSend.Text);
335 | serialPort.Write(byteBuffer, 0, byteBuffer.Length);
336 | SendMessage(strSend);
337 | }
338 | else
339 | {
340 | MessageBox.Show("请选择数据发送的格式!", "信息提示",
341 | MessageBoxButtons.OK, MessageBoxIcon.Information);
342 | }
343 | }
344 | #endregion
345 |
346 | #region timeSend_Tick 定时器Timer
347 | ///
348 | /// 定时发送的定时器Timer
349 | ///
350 | private void timeSend_Tick(object sender, EventArgs e)
351 | {
352 | //转换时间间隔
353 | string strSecond = txtSecond.Text;
354 |
355 | try
356 | {
357 | //Interval的单位是ms
358 | int isecond = int.Parse(strSecond) * 1000;
359 | timeSend.Interval = isecond;
360 |
361 | if (timeSend.Enabled==true)
362 | {
363 | //如果timeSend空间是可用状态,用按钮的PerformClick()方法生成按钮的点击事件。
364 | btnSend.PerformClick();
365 | }
366 | }
367 | catch (Exception ex)
368 | {
369 | //若出现异常,就将Timer控件状态设为不可用,然后抛出异常提示
370 | timeSend.Enabled = false;
371 | MessageBox.Show("设置的时间间隔格式错误!\n"+ex.Message, "异常提示信息",
372 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
373 | }
374 | }
375 | #endregion
376 |
377 | #region btnSwitch_Click 打开/关闭串口按钮
378 | ///
379 | /// 打开/关闭串口的按钮事件
380 | ///
381 | private void btnSwitch_Click(object sender, EventArgs e)
382 | {
383 | if (!serialPort.IsOpen)
384 | {
385 | try
386 | {
387 | //设置串口号
388 | string serialName = cbSerial.SelectedItem.ToString();
389 | serialPort.PortName = serialName;
390 |
391 | //对串口参数进行设置
392 | string strBaudRate = cbBaudRate.Text;
393 | string strDateBits = cbDataBits.Text;
394 | string strStopBits = cbStop.Text;
395 |
396 | Int32 iBaudRate = Convert.ToInt32(strBaudRate);
397 | Int32 iDateBits = Convert.ToInt32(strDateBits);
398 |
399 | //设置波特率
400 | serialPort.BaudRate = iBaudRate;
401 | //设置数据位
402 | serialPort.DataBits = iDateBits;
403 | //设置停止位
404 | switch (cbStop.Text)
405 | {
406 | case "1": serialPort.StopBits = StopBits.One; break;
407 | case "1.5": serialPort.StopBits = StopBits.OnePointFive; break;
408 | case "2": serialPort.StopBits = StopBits.Two; break;
409 | default:
410 | MessageBox.Show("停止位参数不正确", "异常提示信息",
411 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
412 | break;
413 | }
414 | //设置校验位
415 | switch (cbParity.Text)
416 | {
417 | case "无": serialPort.Parity = Parity.None; break;
418 | case "奇校验": serialPort.Parity = Parity.Odd; break;
419 | case "偶校验": serialPort.Parity = Parity.Even; break;
420 | default:
421 | MessageBox.Show("校验位参数不正确!", "异常提示信息",
422 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
423 | break;
424 | }
425 |
426 | //如果串口为打开状态,就先关闭一下来初始化串口
427 | if (serialPort.IsOpen==true)
428 | {
429 | serialPort.Close();
430 | }
431 |
432 | //状态栏设置
433 | tsSpNum.Text = "串口号:" + serialPort.PortName + "|";
434 | tsBaudRate.Text = "波特率:" + serialPort.BaudRate + "|";
435 | tsDataBits.Text = "数据位:" + serialPort.DataBits + "|";
436 | tsStopBits.Text = "停止位:" + serialPort.StopBits + "|";
437 | tsParity.Text = "校验位:" + serialPort.Parity;
438 |
439 | //设置必要的控件为不可用状态
440 | SettingControls(0);
441 |
442 | //打开串口
443 | serialPort.Open();
444 | //将按钮内容设置为"关闭串口"
445 | btnSwitch.Text = "关闭串口";
446 | }
447 | catch (Exception ex)
448 | {
449 | MessageBox.Show("错误:" + ex.Message, "异常提示信息",
450 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
451 | timeSend.Enabled = false;
452 |
453 | //设置必要的控件为可用状态
454 | SettingControls(1);
455 | return;
456 | }
457 | }
458 | else
459 | {
460 | //状态栏设置
461 | tsSpNum.Text = "串口号:未指定|";
462 | tsBaudRate.Text = "波特率:未指定|";
463 | tsDataBits.Text = "数据位:未指定|";
464 | tsStopBits.Text = "停止位:未指定|";
465 | tsParity.Text = "校验位:未指定|";
466 |
467 | //恢复控件功能,设置必要控件为可用状态
468 | SettingControls(1);
469 |
470 | //关闭串口
471 | serialPort.Close();
472 |
473 | //设置按钮内容为"打开串口"
474 | btnSwitch.Text = "打开串口";
475 |
476 | //关闭计时器Timer
477 | timeSend.Enabled = false;
478 | }
479 | }
480 | #endregion
481 |
482 | #region Form1_FormClosing 程序窗口关闭事件
483 | ///
484 | /// 程序窗口关闭时的事件
485 | ///
486 | private void Form1_FormClosing(object sender, FormClosingEventArgs e)
487 | {
488 | //保存配置到INI文件,关闭打开的串口
489 | INIFILE.Profile.SaveProfile();
490 | serialPort.Close();
491 | }
492 | #endregion
493 |
494 | #region btnSave_Click 保存设置按钮
495 | ///
496 | /// "保存设置"按钮点击事件
497 | ///
498 | private void btnSave_Click(object sender, EventArgs e)
499 | {
500 | //设置各"串口设置"
501 | string strStopBits = cbStop.Text;
502 | Int32 iBaudRate = Convert.ToInt32(cbBaudRate.Text);
503 | Int32 iDataBits = Convert.ToInt32(cbDataBits.Text);
504 |
505 | //保存波特率设置
506 | Profile.G_BAUDRATE = iBaudRate + "";
507 | //保存数据位设置
508 | Profile.G_DATABITS = iDataBits + "";
509 | //保存停止位设置
510 | switch (cbStop.Text)
511 | {
512 | case "1": Profile.G_STOP = "1"; break;
513 | case "1.5": Profile.G_STOP = "1.5"; break;
514 | case "2": Profile.G_STOP = "2"; break;
515 | default:
516 | MessageBox.Show("停止位参数不正确", "异常提示信息",
517 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
518 | break;
519 | }
520 | //保存校验位设置
521 | switch (cbParity.Text)
522 | {
523 | case "无": Profile.G_PARITY = "NONE"; break;
524 | case "奇校验": Profile.G_PARITY = "ODD"; break;
525 | case "偶校验": Profile.G_PARITY = "EVEN"; break;
526 | default:
527 | MessageBox.Show("校验位参数不正确", "异常提示信息",
528 | MessageBoxButtons.OK, MessageBoxIcon.Warning);
529 | break;
530 | }
531 |
532 | //保存设置
533 | Profile.SaveProfile();
534 |
535 | //保存成功提示
536 | MessageBox.Show("设置保存成功!","信息提示",
537 | MessageBoxButtons.OK,MessageBoxIcon.Information);
538 | }
539 | #endregion
540 |
541 | #region txtSend_KeyPress 发送框输入校验
542 | ///
543 | /// 对发送框的输入进行校验
544 | ///
545 | private void txtSend_KeyPress(object sender, KeyPressEventArgs e)
546 | {
547 | if (rbSend16.Checked == true)
548 | {
549 | //正则匹配,\b表示退格键(对16进制的输入进行格式校验)
550 | string pattern = "[0-9a-fA-F]|\b|0x|0X| ";
551 | Regex regex = new Regex(pattern);
552 | Match match = regex.Match(e.KeyChar.ToString());
553 |
554 | if (match.Success)
555 | {
556 | e.Handled = false;
557 | }
558 | else
559 | {
560 | e.Handled = true;
561 | }
562 | }
563 | else
564 | {
565 | e.Handled = false;
566 | }
567 | }
568 | #endregion
569 |
570 | #region txtSecond_KeyPress 定时输入校验
571 | ///
572 | /// 对定时输入的时间进行校验
573 | ///
574 | private void txtSecond_KeyPress(object sender, KeyPressEventArgs e)
575 | {
576 | string pattern = "[0-9]|\b";
577 | Regex regex = new Regex(pattern);
578 | Match match = regex.Match(e.KeyChar.ToString());
579 |
580 | if (match.Success)
581 | {
582 | e.Handled = false;
583 | }
584 | else
585 | {
586 | e.Handled = true;
587 | }
588 | }
589 | #endregion
590 |
591 | #region Method ByteToHex and HexToByte Byte字节数组、Hex16进制和字符串之间转换的方法
592 |
593 | //byte字节数组转16进制
594 | private string ByteToHex(byte[] comByte)
595 | {
596 | StringBuilder builder = new StringBuilder(comByte.Length * 3);
597 |
598 | foreach (byte data in comByte)
599 | {
600 | builder.Append(Convert.ToString(data,16).PadLeft(2,'0').PadRight(3,' '));
601 | }
602 | return builder.ToString().ToUpper();
603 | }
604 |
605 | //16进制转字节数组
606 | private byte[] HexToByte(string msg)
607 | {
608 | msg = msg.Replace(" ", "");
609 | msg = msg.Replace("0x", "");
610 | msg = msg.Replace("0X", "");
611 |
612 | byte[] comBuffer = new byte[msg.Length / 2];
613 |
614 | for (int i = 0; i < msg.Length; i+=2)
615 | {
616 | comBuffer[i / 2] = (byte)Convert.ToByte(msg.Substring(i, 2), 16);
617 | }
618 | return comBuffer;
619 | }
620 |
621 | //字符串转字节型数组
622 | private byte[] StringToByte(string msgtxt)
623 | {
624 | return System.Text.Encoding.UTF8.GetBytes(msgtxt);
625 | }
626 |
627 | //字节型数组转字符串
628 | private string ByteToString(byte[] buffer)
629 | {
630 | return System.Text.Encoding.UTF8.GetString(buffer);
631 | }
632 | #endregion
633 |
634 | #region rbSend16_CheckedChanged 发送方式改变时清空原来的输入框
635 |
636 | //当发送方式发生变化时更改cbSendHex的可用状态并清空当前发送框的内容
637 | private void rbSend16_CheckedChanged(object sender, EventArgs e)
638 | {
639 | if (rbSend16.Checked==true)
640 | {
641 | cbSendHex.Enabled = false;
642 | btnSendCRC.Enabled = true;
643 | txtStrTo16.Text = "";
644 | }
645 | else
646 | {
647 | cbSendHex.Enabled = true;
648 | btnSendCRC.Enabled = false;
649 | }
650 | txtSend.Text = "";
651 | }
652 | #endregion
653 |
654 | #region Method SettingControls 设置控件可用状态的方法
655 | //用于设置控件的可用状态,canUse 参数-> 1:可用 0:不可用
656 | private void SettingControls(int canUse)
657 | {
658 | if (canUse==1)
659 | {
660 | cbSerial.Enabled = true;
661 | cbBaudRate.Enabled = true;
662 | cbDataBits.Enabled = true;
663 | cbStop.Enabled = true;
664 | cbParity.Enabled = true;
665 | }
666 | else if(canUse==0)
667 | {
668 | cbSerial.Enabled = false;
669 | cbBaudRate.Enabled = false;
670 | cbDataBits.Enabled = false;
671 | cbStop.Enabled = false;
672 | cbParity.Enabled = false;
673 | }
674 | }
675 | #endregion
676 |
677 | #region 用于将输入框的字符串实时翻译为16进制
678 | //用于监听cbSendHex按钮的状态
679 | private void cbSendHex_CheckedChanged(object sender, EventArgs e)
680 | {
681 | //如果cbSendHex按钮选中就翻译发送框的内容
682 | if (cbSendHex.Checked==true)
683 | {
684 | txtStrTo16.Text = ByteToHex(StringToByte(txtSend.Text));
685 | }
686 | else
687 | {
688 | txtStrTo16.Text = "";
689 | }
690 | }
691 |
692 | //用于监听txtSend的文本输入,如果txtSend内容发生变化,txtStrTo16实时将字符串翻译为16进制
693 | private void txtSend_TextChanged(object sender, EventArgs e)
694 | {
695 | if (cbSendHex.Checked == true&&rbSend16.Checked==false)
696 | {
697 | txtStrTo16.Text = ByteToHex(StringToByte(txtSend.Text));
698 | }
699 | }
700 | #endregion
701 |
702 | private void btnSendCRC_Click(object sender, EventArgs e)
703 | {
704 | //发送前判断串口是否打开
705 | if (!serialPort.IsOpen)
706 | {
707 | MessageBox.Show("请先打开串口!", "提示信息",
708 | MessageBoxButtons.OK, MessageBoxIcon.Information);
709 | return;
710 | }
711 | //判断cbTimeSend是否被勾选,来决定是否启动Timer控件进行定时发送
712 | if (cbTimeSend.Checked)
713 | {
714 | timeSend.Enabled = true;
715 | }
716 | else
717 | {
718 | timeSend.Enabled = false;
719 | }
720 |
721 | if (rbSend16.Checked == true)
722 | {
723 | try
724 | {
725 | //如果以16进制带CRC校验形式发送,调用ModbusCRC16的方法将16进制字符串转换为带CRC的字节数组
726 | byte[] byteBuffer=ModbusCRC16.getSendBuf(txtSend.Text);
727 |
728 | serialPort.Write(byteBuffer, 0, byteBuffer.Length);
729 |
730 | SendMessage(ByteToHex(byteBuffer));
731 | }
732 | catch (Exception ex)
733 | {
734 | MessageBox.Show("16进制数的格式或长度不正确,请检查格式后重新发送。\n"+ex.Message, "信息提示",
735 | MessageBoxButtons.OK, MessageBoxIcon.Information);
736 | }
737 |
738 | }
739 | else
740 | {
741 | MessageBox.Show("请选择数据发送的格式!", "信息提示",
742 | MessageBoxButtons.OK, MessageBoxIcon.Information);
743 | }
744 |
745 | }
746 | }
747 | }
748 |
--------------------------------------------------------------------------------