diff --git a/App.config b/App.config new file mode 100644 index 0000000..56efbc7 --- /dev/null +++ b/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/App.xaml b/App.xaml new file mode 100644 index 0000000..233eae4 --- /dev/null +++ b/App.xaml @@ -0,0 +1,9 @@ + + + + + diff --git a/App.xaml.cs b/App.xaml.cs new file mode 100644 index 0000000..c7fb8ee --- /dev/null +++ b/App.xaml.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; + +namespace DyeingComputer +{ + /// + /// App.xaml 的交互逻辑 + /// + public partial class App : Application + { + + public App() + { + this.Startup += new StartupEventHandler(App_Startup); + this.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException); + } + System.Threading.Mutex mutex; + void App_Startup(object sender, StartupEventArgs e) //程序只允许启动一次 + { + bool ret; + mutex = new System.Threading.Mutex(true, "ElectronicNeedleTherapySystem", out ret); + if (!ret) + { + MessageBox.Show("The program has been launched"); + Environment.Exit(0); + } + } + + protected override void OnStartup(StartupEventArgs e) //跟踪报错信息 + { + base.OnStartup(e); + //UI线程的异常捕捉 + this.DispatcherUnhandledException += App_DispatcherUnhandledException; + } + + private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) + { + e.Handled = true; + if (e.Exception.InnerException == null) + { + MessageBox.Show("发生了一个无法处理的错误!请联系SUNLIGHT处理!" + + "(1)错误" + Environment.NewLine + + "(2)错误源:" + e.Exception.Source + Environment.NewLine + // + (3)详细信息:" + e.Exception.Message + Environment.NewLine + // + "(4)报错区域:" + e.Exception.StackTrace + ); + } + else + { + MessageBox.Show("发生了一个无法处理的错误!请联系SUNLIGHT处理!" + + "(1)错误" + Environment.NewLine + // + "(2)错误源:" + e.Exception.InnerException.Source + Environment.NewLine + + "(3)错误信息:" + e.Exception.Message + Environment.NewLine + // + "(4)详细信息:" + e.Exception.InnerException.Message + Environment.NewLine + // + "(5)报错区域:" + e.Exception.InnerException.StackTrace + ); + } + + string Log_time = DateTime.Now.ToString("yyyy-MM-dd"); + string logpath = System.Environment.CurrentDirectory + "\\ERR";//日志文件目录 + //string logPathtxt = "" + System.Environment.CurrentDirectory + "\\Log\\"+ Log_time + "Log.txt";//日志文件 + // System.IO.DirectoryInfo log = new System.IO.DirectoryInfo();//生成日志文件目录 + string log_path = logpath + "\\ERR" + Log_time + ".txt"; + string Log_timehms = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); + if (Directory.Exists(logpath))//检查日志路径 + { + if (!File.Exists(log_path))//检查文件并写入 + { + FileStream fs = new FileStream(log_path, FileMode.CreateNew, FileAccess.Write);//创建文件 + StreamWriter wr = new StreamWriter(fs);//创建文件 + wr.Close(); + FileStream fil = new FileStream(log_path, FileMode.Append, FileAccess.Write);//创建写入文件 + StreamWriter wfil = new StreamWriter(fil);//创建文件 + wfil.WriteLine("[" + Log_timehms + "];[Error] ||" + Environment.NewLine.ToString()); + wfil.WriteLine("[" + Log_timehms + "];[Error source] ||" + e.Exception.Source.ToString() + Environment.NewLine.ToString()); + wfil.WriteLine("[" + Log_timehms + "];[Error message] ||" + e.Exception.Message.ToString() + Environment.NewLine.ToString()); + wfil.WriteLine("[" + Log_timehms + "];[Error area] ||" + e.Exception.StackTrace.ToString()); + wfil.Close(); + } + else + { + FileStream fs = new FileStream(log_path, FileMode.Append, FileAccess.Write);//创建写入文件 + StreamWriter wr = new StreamWriter(fs);//创建文件 + wr.WriteLine("[" + Log_timehms + "];[Error] ||" + Environment.NewLine.ToString()); + wr.WriteLine("[" + Log_timehms + "];[Error source] ||" + e.Exception.Source.ToString() + Environment.NewLine.ToString()); + wr.WriteLine("[" + Log_timehms + "];[Error message] ||" + e.Exception.Message.ToString() + Environment.NewLine.ToString()); + wr.WriteLine("[" + Log_timehms + "];[Error area] ||" + e.Exception.StackTrace.ToString()); + wr.Close(); + } + } + else + { + DirectoryInfo directoryInfo = new DirectoryInfo(logpath); + directoryInfo.Create(); + } + } + /// + /// 启动初始页面 + /// + + private void Application_Startup(object sender, StartupEventArgs e) + { + Application.Current.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);//和MainWindwo同一目录 + } + + } +} diff --git a/DyeingComputer.csproj b/DyeingComputer.csproj new file mode 100644 index 0000000..724a838 --- /dev/null +++ b/DyeingComputer.csproj @@ -0,0 +1,112 @@ + + + + + Debug + AnyCPU + {18FD96BD-D3DD-46DA-BE92-CA942F27D4DD} + WinExe + DyeingComputer + DyeingComputer + v4.7.2 + 512 + {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + 4 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + 4.0 + + + + + + + + MSBuild:Compile + Designer + + + + + + + + + + + + + + + MSBuild:Compile + Designer + + + App.xaml + Code + + + MainWindow.xaml + Code + + + + + Code + + + True + True + Resources.resx + + + True + Settings.settings + True + + + ResXFileCodeGenerator + Resources.Designer.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + \ No newline at end of file diff --git a/DyeingComputer.sln b/DyeingComputer.sln new file mode 100644 index 0000000..09a7410 --- /dev/null +++ b/DyeingComputer.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.10.35122.118 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DyeingComputer", "DyeingComputer.csproj", "{18FD96BD-D3DD-46DA-BE92-CA942F27D4DD}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {18FD96BD-D3DD-46DA-BE92-CA942F27D4DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18FD96BD-D3DD-46DA-BE92-CA942F27D4DD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18FD96BD-D3DD-46DA-BE92-CA942F27D4DD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18FD96BD-D3DD-46DA-BE92-CA942F27D4DD}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {23C27729-172E-4ACB-8978-76C890F41C29} + EndGlobalSection +EndGlobal diff --git a/MainWindow.xaml b/MainWindow.xaml new file mode 100644 index 0000000..0ba3601 --- /dev/null +++ b/MainWindow.xaml @@ -0,0 +1,12 @@ + + + + + diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs new file mode 100644 index 0000000..1287c8e --- /dev/null +++ b/MainWindow.xaml.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace DyeingComputer +{ + /// + /// MainWindow.xaml 的交互逻辑 + /// + public partial class MainWindow : Window + { + public MainWindow() + { + InitializeComponent(); + } + } +} diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1da8fef --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("DyeingComputer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DyeingComputer")] +[assembly: AssemblyCopyright("Copyright © 2024")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +//若要开始生成可本地化的应用程序,请设置 +//.csproj 文件中的 CultureYouAreCodingWith +//在 中。例如,如果你使用的是美国英语。 +//使用的是美国英语,请将 设置为 en-US。 然后取消 +//对以下 NeutralResourceLanguage 特性的注释。 更新 +//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。 + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //主题特定资源词典所处位置 + //(未在页面中找到资源时使用, + //或应用程序资源字典中找到时使用) + ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置 + //(未在页面中找到资源时使用, + //、应用程序或任何主题专用资源字典中找到时使用) +)] + + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 +//通过使用 "*",如下所示: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Properties/Resources.Designer.cs b/Properties/Resources.Designer.cs new file mode 100644 index 0000000..ceced02 --- /dev/null +++ b/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + +namespace DyeingComputer.Properties +{ + + + /// + /// 强类型资源类,用于查找本地化字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// 返回此类使用的缓存 ResourceManager 实例。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DyeingComputer.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Properties/Resources.resx b/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Properties/Settings.Designer.cs b/Properties/Settings.Designer.cs new file mode 100644 index 0000000..d24ef79 --- /dev/null +++ b/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DyeingComputer.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Properties/Settings.settings b/Properties/Settings.settings new file mode 100644 index 0000000..033d7a5 --- /dev/null +++ b/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/UserClass/CRCcheck16.cs b/UserClass/CRCcheck16.cs new file mode 100644 index 0000000..f511e8d --- /dev/null +++ b/UserClass/CRCcheck16.cs @@ -0,0 +1,190 @@ +using System; +using System.Text; + +namespace formula_manage.UserClass +{ + /// + /// CRC校验 + /// + public class CRCcheck16 + { + + #region CRC16 + public static byte[] CRC16(byte[] data) + { + int len = data.Length; + if (len > 0) + { + ushort crc = 0xFFFF; + + for (int i = 0; i < len; i++) + { + crc = (ushort)(crc ^ (data[i])); + for (int j = 0; j < 8; j++) + { + crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1); + } + } + byte hi = (byte)((crc & 0xFF00) >> 8); //高位置 + byte lo = (byte)(crc & 0x00FF); //低位置 + + return new byte[] { hi, lo }; + } + return new byte[] { 0, 0 }; + } + #endregion + + #region ToCRC16 + public static string ToCRC16(string content) + { + return ToCRC16(content, Encoding.UTF8); + } + + public static string ToCRC16(string content, bool isReverse) + { + return ToCRC16(content, Encoding.UTF8, isReverse); + } + + public static string ToCRC16(string content, Encoding encoding) + { + return ByteToString(CRC16(encoding.GetBytes(content)), true); + } + + public static string ToCRC16(string content, Encoding encoding, bool isReverse) + { + return ByteToString(CRC16(encoding.GetBytes(content)), isReverse); + } + + public static string ToCRC16(byte[] data) + { + return ByteToString(CRC16(data), true); + } + + public static string ToCRC16(byte[] data, bool isReverse) + { + return ByteToString(CRC16(data), isReverse); + } + #endregion + + #region ToModbusCRC16 + public static string ToModbusCRC16(string s) + { + return ToModbusCRC16(s, true); + } + + public static string ToModbusCRC16(string s, bool isReverse) + { + return ByteToString(CRC16(StringToHexByte(s)), isReverse); + } + + public static string ToModbusCRC16(byte[] data) + { + return ToModbusCRC16(data, true); + } + + public static string ToModbusCRC16(byte[] data, bool isReverse) + { + return ByteToString(CRC16(data), isReverse); + } + #endregion + + #region ByteToString + public static string ByteToString(byte[] arr, bool isReverse) + { + try + { + byte hi = arr[0], lo = arr[1]; + return Convert.ToString(isReverse ? hi + lo * 0x100 : hi * 0x100 + lo, 16).ToUpper().PadLeft(4, '0'); + } + catch (Exception ex) { throw (ex); } + } + + public static string ByteToString(byte[] arr) + { + try + { + return ByteToString(arr, true); + } + catch (Exception ex) { throw (ex); } + } + #endregion + + #region StringToHexString + public static string StringToHexString(string str) + { + StringBuilder s = new StringBuilder(); + foreach (short c in str.ToCharArray()) + { + s.Append(c.ToString("X4")); + } + return s.ToString(); + } + #endregion + + #region StringToHexByte + private static string ConvertChinese(string str) + { + StringBuilder s = new StringBuilder(); + foreach (short c in str.ToCharArray()) + { + if (c <= 0 || c >= 127) + { + s.Append(c.ToString("X4")); + } + else + { + s.Append((char)c); + } + } + return s.ToString(); + } + + private static string FilterChinese(string str) + { + StringBuilder s = new StringBuilder(); + foreach (short c in str.ToCharArray()) + { + if (c > 0 && c < 127) + { + s.Append((char)c); + } + } + return s.ToString(); + } + + /// + /// 字符串转16进制字符数组 + /// + /// + /// + public static byte[] StringToHexByte(string str) + { + return StringToHexByte(str, false); + } + + /// + /// 字符串转16进制字符数组 + /// + /// + /// 是否过滤掉中文字符 + /// + public static byte[] StringToHexByte(string str, bool isFilterChinese) + { + string hex = isFilterChinese ? FilterChinese(str) : ConvertChinese(str); + + //清除所有空格 + hex = hex.Replace(" ", ""); + //若字符个数为奇数,补一个0 + hex += hex.Length % 2 != 0 ? "0" : ""; + + byte[] result = new byte[hex.Length / 2]; + for (int i = 0, c = result.Length; i < c; i++) + { + result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); + } + return result; + } + #endregion + + } +} diff --git a/UserClass/DataGridHelper.cs b/UserClass/DataGridHelper.cs new file mode 100644 index 0000000..18adf48 --- /dev/null +++ b/UserClass/DataGridHelper.cs @@ -0,0 +1,52 @@ +using System; +using System.Windows; +using System.Windows.Controls; + +namespace formula_manage.UserClass +{ + /// + /// 实时更新datagrid + /// 调用示例:DataGridHelper.SetRealTimeCommit(Grid, true); Grid为对象控件名 + /// + public static class DataGridHelper + { + public static void SetRealTimeCommit(DataGrid dataGrid, bool isRealTime) + { + dataGrid.SetValue(RealTimeCommitProperty, isRealTime); + } + + public static bool GetRealTimeCommit(DataGrid dataGrid) + { + return (bool)dataGrid.GetValue(RealTimeCommitProperty); + } + + public static readonly DependencyProperty RealTimeCommitProperty = + DependencyProperty.RegisterAttached("RealTimeCommit", typeof(bool), + typeof(DataGridHelper), + new PropertyMetadata(false, RealTimeCommitCallBack)); + + private static void RealTimeCommitCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var dg = d as DataGrid; + if (dg == null) + return; + EventHandler ceHandler = delegate (object xx, DataGridCellEditEndingEventArgs yy) + { + var flag = GetRealTimeCommit(dg); + if (!flag) + return; + var cellContent = yy.Column.GetCellContent(yy.Row); + if (cellContent != null && cellContent.BindingGroup != null) + cellContent.BindingGroup.CommitEdit(); + }; + dg.CellEditEnding += ceHandler; + RoutedEventHandler eh = null; + eh = (xx, yy) => + { + dg.Unloaded -= eh; + dg.CellEditEnding -= ceHandler; + }; + dg.Unloaded += eh; + } + } +} diff --git a/UserClass/DataTableForToObservableCollection.cs b/UserClass/DataTableForToObservableCollection.cs new file mode 100644 index 0000000..8576c1b --- /dev/null +++ b/UserClass/DataTableForToObservableCollection.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.ObjectModel; +using System.Data; +using System.Reflection; + +namespace formula_manage.UserClass +{ + internal class DataTableToObservableCollection //数据表到可观察集合 + { + public ObservableCollection ToObservableCollection(DataTable dt) where T : class, new() + { + Type t = typeof(T); + PropertyInfo[] propertys = t.GetProperties(); + ObservableCollection lst = new ObservableCollection(); + string typeName = string.Empty; + foreach (DataRow dr in dt.Rows) + { + T entity = new T(); + foreach (PropertyInfo pi in propertys) + { + typeName = pi.Name; + if (dt.Columns.Contains(typeName)) + { + if (!pi.CanWrite) continue; + object value = dr[typeName]; + if (value == DBNull.Value) continue; + if (pi.PropertyType == typeof(string)) + { + pi.SetValue(entity, value.ToString(), null); + } + else if (pi.PropertyType == typeof(int) || pi.PropertyType == typeof(int?)) + { + pi.SetValue(entity, int.Parse(value.ToString()), null); + } + else if (pi.PropertyType == typeof(DateTime?) || pi.PropertyType == typeof(DateTime)) + { + pi.SetValue(entity, DateTime.Parse(value.ToString()), null); + } + else if (pi.PropertyType == typeof(float)) + { + pi.SetValue(entity, float.Parse(value.ToString()), null); + } + else if (pi.PropertyType == typeof(double)) + { + pi.SetValue(entity, double.Parse(value.ToString()), null); + } + else + { + pi.SetValue(entity, value, null); + } + } + } + lst.Add(entity); + } + return lst; + } + + } +} diff --git a/UserClass/HardwareSN.cs b/UserClass/HardwareSN.cs new file mode 100644 index 0000000..45de8a4 --- /dev/null +++ b/UserClass/HardwareSN.cs @@ -0,0 +1,95 @@ +using System.Management; + +namespace formula_manage.UserClass +{ + /// + /// 获取硬件SN + /// + internal class HardwareSN + { + /// + /// 获取cpuid + /// + public static string GetCPUSerialNumber() + { + try + { + ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor"); + string cpuSerialNumber = ""; + foreach (ManagementObject mo in searcher.Get()) + { + cpuSerialNumber = mo["ProcessorId"].ToString().Trim(); + break; + } + return cpuSerialNumber; + } + catch + { + return ""; + } + } + /// + /// 获取主板id + /// + public static string GetBIOSSerialNumber() + { + try + { + ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_BIOS"); + string biosSerialNumber = ""; + foreach (ManagementObject mo in searcher.Get()) + { + biosSerialNumber = mo.GetPropertyValue("SerialNumber").ToString().Trim(); + break; + } + return biosSerialNumber; + } + catch + { + return ""; + } + } + /// + /// 获取硬盘id + /// + public static string GetHardDiskSerialNumber() + { + try + { + ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia"); + string hardDiskSerialNumber = ""; + foreach (ManagementObject mo in searcher.Get()) + { + hardDiskSerialNumber = mo["SerialNumber"].ToString().Trim(); + break; + } + return hardDiskSerialNumber; + } + catch + { + return ""; + } + } + /// + /// 获取网卡id + /// + public static string GetNetCardMACAddress() + { + try + { + ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))"); + string netCardMACAddress = ""; + foreach (ManagementObject mo in searcher.Get()) + { + netCardMACAddress = mo["MACAddress"].ToString().Trim(); + break; + } + return netCardMACAddress; + } + catch + { + return ""; + } + } + } +} diff --git a/UserClass/IniFile.cs b/UserClass/IniFile.cs new file mode 100644 index 0000000..c43b367 --- /dev/null +++ b/UserClass/IniFile.cs @@ -0,0 +1,52 @@ +using System.Runtime.InteropServices; +using System.Text; + +namespace formula_manage.UserClass +{ + internal class IniFile + { + public class IniFiles + { + public string path; + [DllImport("kernel32")] //返回0表示失败,非0为成功 + private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); + [DllImport("kernel32")] //返回取得字符串缓冲区的长度 + private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); + /// + /// 保存ini文件的路径 + /// 调用示例:var ini = IniFiles("C:\file.ini"); + /// + /// + public IniFiles(string iniPath) + { + this.path = iniPath; + } + /// + /// 写Ini文件 + /// 调用示例:ini.IniWritevalue("Server","name","localhost"); + /// + /// [缓冲区] + /// 键 + /// 值 + public void IniWritevalue(string Section, string Key, string value) + { + WritePrivateProfileString(Section, Key, value, this.path); + } + /// + /// 读Ini文件 + /// 调用示例:ini.IniWritevalue("Server","name"); + /// + /// [缓冲区] + /// 键 + /// + public string IniReadvalue(string Section, string Key) + { + StringBuilder temp = new StringBuilder(255); + + int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path); + return temp.ToString(); + } + + } + } +} diff --git a/UserClass/LogDataRead.cs b/UserClass/LogDataRead.cs new file mode 100644 index 0000000..b43eb81 --- /dev/null +++ b/UserClass/LogDataRead.cs @@ -0,0 +1,76 @@ +using System.Text; +using System.Windows.Controls; +using System.Windows.Documents; +using System.Windows.Media; + +namespace formula_manage.UserClass +{ + public static class LogDataRead + { + private const int MaxCount = 1000; + private static int Count = 0; + private static RichTextBox textControl; + private static InlineCollection inlines; + + //设置主控件 + public static void SetTextControl(RichTextBox _textBox) + { + textControl = _textBox; + Paragraph graph = new Paragraph(); + inlines = graph.Inlines; + textControl.Document.Blocks.Add(graph); + } + + //输出黑色消息 + public static void Info(string format, params object[] args) + { + AppendText(Brushes.Black, format, args); + } + + //输出绿色消息 + public static void Suc(string format, params object[] args) + { + AppendText(Brushes.DarkGreen, format, args); + } + + //输出黄色消息 + public static void Warning(string format, params object[] args) + { + AppendText(Brushes.DarkOrange, format, args); + } + + //输出红色消息 + public static void Error(string format, params object[] args) + { + AppendText(Brushes.Red, format, args); + } + + //清除日志 + public static void Clear() + { + Count = 0; + inlines.Clear(); + textControl.ScrollToEnd(); + } + + private static void AppendText(Brush color, string format, params object[] args) + { + textControl.BeginChange(); + StringBuilder builder = new StringBuilder(); + builder.Append("["); + builder.Append(Count++); + builder.Append("] : "); + builder.Append(string.Format(format, (object[])args)); + builder.Append("\n"); + string str = builder.ToString(); + inlines.Add(new Run(str) { Foreground = color }); + if (inlines.Count > MaxCount) + { + inlines.Remove(inlines.FirstInline); + } + textControl.ScrollToEnd(); + textControl.EndChange(); + } + + } +} diff --git a/UserClass/LogGing.cs b/UserClass/LogGing.cs new file mode 100644 index 0000000..637194a --- /dev/null +++ b/UserClass/LogGing.cs @@ -0,0 +1,37 @@ +using System; +using System.IO; + +namespace formula_manage.UserClass +{ + public class LogGing + { + public static void LogGingDATA(string dat) + { + string logpath = System.Environment.CurrentDirectory + "\\Log";//日志文件目录 + string logPath = "" + System.Environment.CurrentDirectory + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//日志文件 + string Log_time = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]:"; + + if (Directory.Exists(logpath))//检查日志路径 + { + if (!File.Exists(logPath))//检查日志文件并写入启动日志 + { + FileStream fs = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write);//创建写入文件 + StreamWriter wr = new StreamWriter(fs);//创建文件 + wr.WriteLine(Log_time + dat); + wr.Close(); + } + else + { + FileStream fs = new FileStream(logPath, FileMode.Append, FileAccess.Write); + StreamWriter wr = new StreamWriter(fs);//创建文件 + wr.WriteLine(Log_time + dat); + wr.Close(); } + } + else + { + DirectoryInfo directoryInfo = new DirectoryInfo(logpath); + directoryInfo.Create();//创建日志路径 + } + } + } +} diff --git a/UserClass/MD5check.cs b/UserClass/MD5check.cs new file mode 100644 index 0000000..b3c2f4d --- /dev/null +++ b/UserClass/MD5check.cs @@ -0,0 +1,59 @@ +using System; +using System.Security.Cryptography; +using System.Text; + +namespace formula_manage.UserClass +{ + /// + /// MD5加密 + /// + internal class MD5check + { + /// + /// 16位MD5加密 + /// + /// + /// + public static string MD5Encrypt16(string password) + { + var md5 = new MD5CryptoServiceProvider(); + string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password)), 4, 8); + t2 = t2.Replace("-", ""); + return t2; + } + /// + /// 32位MD5加密 + /// + /// + /// + public static string MD5Encrypt32(string password) + { + string cl = password; + string pwd = ""; + MD5 md5 = MD5.Create(); //实例化一个md5对像 + // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择  + byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); + // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得 + for (int i = 0; i < s.Length; i++) + { + // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 + pwd = pwd + s[i].ToString("X"); + } + return pwd; + } + /// + /// 64位MD5加密 + /// + /// + /// + public static string MD5Encrypt64(string password) + { + string cl = password; + //string pwd = ""; + MD5 md5 = MD5.Create(); //实例化一个md5对像 + // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择  + byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); + return Convert.ToBase64String(s); + } + } +} diff --git a/UserClass/PressKey.cs b/UserClass/PressKey.cs new file mode 100644 index 0000000..e0da05c --- /dev/null +++ b/UserClass/PressKey.cs @@ -0,0 +1,28 @@ +using System; +using System.Runtime.InteropServices; +using System.Windows.Forms; + +namespace formula_manage.UserClass +{ + internal class PressKey + { + /// + /// 键盘模拟 + /// + [DllImport("user32.dll", SetLastError = true)] + static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo); + public static void PressKeys(Keys key, bool up) + { + const int KEYEVENTF_EXTENDEDKEY = 0x1; + const int KEYEVENTF_KEYUP = 0x2; + if (up) + { + keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, (UIntPtr)0); + } + else + { + keybd_event((byte)key, 0x45, KEYEVENTF_EXTENDEDKEY, (UIntPtr)0); + } + } + } +} diff --git a/UserClass/StrToInt.cs b/UserClass/StrToInt.cs new file mode 100644 index 0000000..b6c50df --- /dev/null +++ b/UserClass/StrToInt.cs @@ -0,0 +1,37 @@ +using System; + +namespace formula_manage.UserClass +{ + /// + /// 字符串转数字 + /// + internal class StrToInt + { + /// + /// 十六进制字符串转十进制 + /// + /// 十六进制字符 + /// + public static int To16Convert10(string str) + { + int res = 0; + try + { + str = str.Trim().Replace(" ", ""); //移除空字符 + //方法1 + res = int.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier); + //方法2 + //int r2 = System.Int32.Parse(str, System.Globalization.NumberStyles.HexNumber); + //Console.WriteLine(r2); + //方法3 + //int r3 = Convert.ToInt32(str, 16); + //Console.WriteLine(r3); + } + catch (Exception) + { + res = 0; + } + return res; + } + } +} diff --git a/UserClass/TCPServer.cs b/UserClass/TCPServer.cs new file mode 100644 index 0000000..d555a2d --- /dev/null +++ b/UserClass/TCPServer.cs @@ -0,0 +1,186 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; + +namespace formula_manage.UserClass +{ + public class TCPServer + { + public static string infoR; + //第一步:调用socket()函数创建一个用于通信的套接字 + public static Socket listenSocket; + + //字典集合:存储IP和Socket的集合 + public static Dictionary OnLineList = new Dictionary(); + + + //当前时间 + private string CurrentTime + { + get { return DateTime.Now.ToString("HH:mm:ss") + Environment.NewLine; } + } + + //编码格式 + public static Encoding econding = Encoding.UTF8; + + public static void Start() + { + //第一步:调用socket()函数创建一个用于通信的套接字 + listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + //第二步:给已经创建的套接字绑定一个端口号,这一般通过设置网络套接口地址和调用Bind()函数来实现 + IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(UserClass.get_local_ip_address.IP_Address()), int.Parse("11080")); + UserClass.LogGing.LogGingDATA("NativeIP = " + UserClass.get_local_ip_address.IP_Address()); + UserClass.LogGing.LogGingDATA("NativePORT = 11080"); + try + { + listenSocket.Bind(endPoint); + } + catch (Exception ex) + { + UserClass.LogGing.LogGingDATA("TCP_NotStart"); + UserClass.LogGing.LogGingDATA(ex.Message); + return; + } + //第三步:调用listen()函数使套接字成为一个监听套接字 + listenSocket.Listen(10); + //ShowMessage("服务器开启成功"); + + //开启一个线程监听 + Task.Run(new Action(() => { ListenConnection(); })); + } + + public static void ListenConnection() + { + while (true) + { + Socket clientSocket = listenSocket.Accept(); + string ip = clientSocket.RemoteEndPoint.ToString(); + //更新在线列表 + // AddOnLine(ip, true); + //更新在线列表集合 + OnLineList.Add(ip, clientSocket); + UserClass.LogGing.LogGingDATA("IP_Online = " + ip); + // ShowMessage(ip + "上线了"); + Task.Run(() => ReceiveMsg(clientSocket)); + } + } + + /// + /// 接收方法 + /// + /// + public static void ReceiveMsg(Socket clientSocket) + { + while (true) + { + //定义一个2M的缓冲区 + byte[] buffer = new byte[1024 * 1024 * 10]; + + int length = -1; + try + { + length = clientSocket.Receive(buffer); + } + catch (Exception) + { + //客户端下线了 + //更新在线列表 + string ip = clientSocket.RemoteEndPoint.ToString(); + UserClass.LogGing.LogGingDATA("IP_Line = " + ip); + // AddOnLine(ip, false); + OnLineList.Remove(ip); //移除ip + break; //退出循环 + } + + if (length == 0) + { + //客户端下线了 + //更新在线列表 + string ip = clientSocket.RemoteEndPoint.ToString(); + UserClass.LogGing.LogGingDATA("IP_Line = " + ip); + // AddOnLine(ip, false); + OnLineList.Remove(ip); + break; + } + else + { + infoR = econding.GetString(buffer, 0, length); + //ShowMessage(info); + string ip = clientSocket.RemoteEndPoint.ToString(); + } + } + + } + /* + /// + /// 在线列表更新 + /// + /// + /// + private void AddOnLine(string clientIp, bool value) + { + Invoke(new Action(() => + { + if (value) + { + this.lst_Online.Items.Add(clientIp); + } + else + { + this.lst_Online.Items.Remove(clientIp); + } + + })); + + } + + + /// + /// 更新接收区 + /// + /// + private void ShowMessage(string info) + { + Invoke(new Action(() => + { + this.txt_Rcv.AppendText(CurrentTime + info + Environment.NewLine); + })); + + } + + */ + /// + /// 消息发送 + /// + public static void Bn_Send(string IP, string DAT) + { + if (OnLineList.ContainsKey(IP)) + { + OnLineList[IP].Send(econding.GetBytes(DAT)); + } + } + + /// + /// 群发功能 + /// + public static void Btn_SendAll(string DAT) + { + foreach (string item in OnLineList.Keys.ToArray()) + { + if (OnLineList.ContainsKey(item)) + { + OnLineList[item].Send(econding.GetBytes(DAT)); + } + } + } + + } +} + + + diff --git a/UserClass/get_local_ip_address.cs b/UserClass/get_local_ip_address.cs new file mode 100644 index 0000000..2754a2c --- /dev/null +++ b/UserClass/get_local_ip_address.cs @@ -0,0 +1,46 @@ +using System.Net.NetworkInformation; +using System.Net.Sockets; + +namespace formula_manage.UserClass +{ + public class get_local_ip_address + { + public static string getLocalIPAddressWithNetworkInterface(NetworkInterfaceType _type)//获取本机ip并以字符串方式返回 + { + string output = ""; + foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) + { + if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up) + { + foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses) + { + if (ip.Address.AddressFamily == AddressFamily.InterNetwork) + { + output = ip.Address.ToString(); + } + } + } + } + return output; + } + + public static string IP_Address() + { + string ip; + + ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Ethernet); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Wireless80211); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Ppp); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Wwanpp); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.TokenRing); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Fddi); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.GenericModem); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.IPOverAtm); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Tunnel); + if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Unknown); + + if (ip == "") ip = "127.0.0.1"; + return ip; + } + } +}