革博士程序V1仓库
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

570 líneas
22 KiB

  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Management;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Text;
  12. using System.Text.RegularExpressions;
  13. using System.Threading.Tasks;
  14. using System.Windows.Forms;
  15. namespace LeatherApp.Utils
  16. {
  17. public static class Util
  18. {
  19. private static Regex RegNumber = new Regex("^[0-9]+$"); //匹配 整数(不可以带正负号)
  20. private static Regex RegDecimal = new Regex("^(-?\\d+)(\\.\\d+)?$"); //浮点 (可以带正负号)
  21. /// <summary>
  22. /// 获取适合大小
  23. /// </summary>
  24. /// <param name="sourceSize"></param>
  25. /// <param name="targetSize"></param>
  26. /// <returns></returns>
  27. public static Size getNewSize(Size sourceSize, Size targetSize)
  28. {
  29. if (sourceSize.Width <= targetSize.Width && sourceSize.Height <= targetSize.Height)
  30. return sourceSize;
  31. int num = sourceSize.Width / targetSize.Width;
  32. int num2 = sourceSize.Height / targetSize.Height;
  33. int num3 = (num < num2) ? num2 : num;
  34. return new Size(sourceSize.Width / num3, sourceSize.Height / num3);
  35. }
  36. /// <summary>
  37. /// 等比计算宽高
  38. /// </summary>
  39. /// <param name="sourceSize"></param>
  40. /// <param name="targetSize"></param>
  41. /// <returns></returns>
  42. public static SizeF getNewSize(SizeF sourceSize, SizeF targetSize)
  43. {
  44. if (sourceSize.Width <= targetSize.Width && sourceSize.Height <= targetSize.Height)
  45. return sourceSize;
  46. float num = sourceSize.Width / targetSize.Width;
  47. float num2 = sourceSize.Height / targetSize.Height;
  48. float num3 = (num < num2) ? num2 : num;
  49. return new SizeF(sourceSize.Width / num3, sourceSize.Height / num3);
  50. }
  51. /// <summary>
  52. /// 写INI文件
  53. /// </summary>
  54. /// <param name="Section">Section</param>
  55. /// <param name="Key">Key</param>
  56. /// <param name="value">value</param>
  57. public static void WriteIniValue(string filePath, string Section, string Key, string value)
  58. {
  59. API.WritePrivateProfileString(Section, Key, value, filePath);
  60. }
  61. /// <summary>
  62. /// 读取INI文件指定部分
  63. /// </summary>
  64. /// <param name="Section">Section</param>
  65. /// <param name="Key">Key</param>
  66. /// <returns>String</returns>
  67. public static string ReadIniValue(string filePath, string Section, string Key)
  68. {
  69. StringBuilder temp = new StringBuilder(255);
  70. int i = API.GetPrivateProfileString(Section, Key, "", temp, 255, filePath);
  71. return temp.ToString().Trim();
  72. }
  73. /// <summary>
  74. /// 整数
  75. /// </summary>
  76. /// <param name="inputData"></param>
  77. /// <returns></returns>
  78. public static bool IsNumber(string inputData)
  79. {
  80. Match m = RegNumber.Match(inputData);
  81. return m.Success;
  82. }
  83. public static bool IsNumber(object inputData)
  84. {
  85. if (inputData == null) return false;
  86. Match m = RegNumber.Match(inputData.ToString());
  87. return m.Success;
  88. }
  89. public static bool IsDecimal(string inputData)
  90. {
  91. Match m = RegDecimal.Match(inputData);
  92. return m.Success;
  93. }
  94. public static bool IsDecimal(object inputData)
  95. {
  96. if (inputData == null) return false;
  97. Match m = RegDecimal.Match(inputData.ToString());
  98. return m.Success;
  99. }
  100. public static string file2Base64(string filePath)
  101. {
  102. return Convert.ToBase64String(File.ReadAllBytes(filePath));
  103. }
  104. /// <summary>
  105. /// 结构体转byte数组
  106. /// </summary>
  107. /// <param name="structObj">要转换的结构体</param>
  108. /// <returns>转换后的byte数组</returns>
  109. public static byte[] StructToBytes(object structObj)
  110. {
  111. int size = Marshal.SizeOf(structObj);
  112. IntPtr buffer = Marshal.AllocHGlobal(size);
  113. try
  114. {
  115. Marshal.StructureToPtr(structObj, buffer, false);
  116. byte[] bytes = new byte[size];
  117. Marshal.Copy(buffer, bytes, 0, size);
  118. return bytes;
  119. }
  120. finally
  121. {
  122. Marshal.FreeHGlobal(buffer);
  123. }
  124. }
  125. /// <summary>
  126. /// byte数组转结构体
  127. /// </summary>
  128. /// <param name="bytes">byte数组</param>
  129. /// <param name="type">结构体类型</param>
  130. /// <returns>转换后的结构体</returns>
  131. public static object BytesToStruct(byte[] bytes, Type strcutType)
  132. {
  133. int size = Marshal.SizeOf(strcutType);
  134. IntPtr buffer = Marshal.AllocHGlobal(size);
  135. try
  136. {
  137. Marshal.Copy(bytes, 0, buffer, size);
  138. return Marshal.PtrToStructure(buffer, strcutType);
  139. }
  140. finally
  141. {
  142. Marshal.FreeHGlobal(buffer);
  143. }
  144. }
  145. /// <summary>
  146. /// 是否为系统不可操作窗体(如桌面、任务栏等)
  147. /// </summary>
  148. /// <returns></returns>
  149. public static bool IsSysWin(IntPtr WinHwnd)
  150. {
  151. if (WinHwnd != IntPtr.Zero)
  152. {
  153. StringBuilder lsbClassName = new StringBuilder(256);
  154. API.GetClassName(WinHwnd, lsbClassName, 256 - 1);
  155. string lsWinClassName = lsbClassName.ToString().ToLower();
  156. return (lsWinClassName == "progman" || lsWinClassName == "shell_traywnd");
  157. }
  158. return false;
  159. }
  160. public static bool DisableDevice(string sDeviceID)
  161. {
  162. try
  163. {
  164. if (sDeviceID == null || sDeviceID.Trim() == "" || !System.IO.File.Exists(System.Environment.SystemDirectory + "\\devcon.exe"))
  165. return false;
  166. string[] lsDeviceIDs = sDeviceID.Split(new char[] { ';', ',' });
  167. ProcessStartInfo info;
  168. for (int i = 0; i < lsDeviceIDs.Length; i++)
  169. {
  170. if (lsDeviceIDs[i].Trim() == "") continue;
  171. info = new ProcessStartInfo();
  172. info.FileName = System.Environment.SystemDirectory + "\\devcon.exe"; // 要启动的程序
  173. info.Arguments = "disable " + lsDeviceIDs[i]; //传递给程序的参数
  174. info.WindowStyle = ProcessWindowStyle.Hidden; //隐藏窗口
  175. Process pro = Process.Start(info); //启动程序
  176. }
  177. return true;
  178. }
  179. catch
  180. {
  181. return false;
  182. }
  183. }
  184. public static bool EnableDevice(string sDeviceID)
  185. {
  186. try
  187. {
  188. if (sDeviceID == null || sDeviceID.Trim() == "" || !System.IO.File.Exists(System.Environment.SystemDirectory + "\\devcon.exe"))
  189. return false;
  190. string[] lsDeviceIDs = sDeviceID.Split(new char[] { ';' });
  191. ProcessStartInfo info;
  192. for (int i = 0; i < lsDeviceIDs.Length; i++)
  193. {
  194. if (lsDeviceIDs[i].Trim() == "") continue;
  195. info = new ProcessStartInfo();
  196. info.FileName = System.Environment.SystemDirectory + "\\devcon.exe"; // 要启动的程序
  197. info.Arguments = "enable " + lsDeviceIDs[i]; //传递给程序的参数
  198. info.WindowStyle = ProcessWindowStyle.Hidden; //隐藏窗口
  199. Process pro = Process.Start(info); //启动程序
  200. }
  201. return true;
  202. }
  203. catch
  204. {
  205. return false;
  206. }
  207. }
  208. /// <summary>
  209. /// 获取时间戳
  210. /// </summary>
  211. public static string GetTimestamp()
  212. {
  213. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  214. DateTime dtNow = DateTime.Now;
  215. TimeSpan toNow = dtNow.Subtract(dtStart);
  216. System.Random rand = new Random();
  217. string timeStamp = toNow.Ticks.ToString() + rand.Next(9);
  218. return timeStamp;
  219. }
  220. /// <summary>
  221. /// 获取MD5串(未转大小写)
  222. /// </summary>
  223. public static string GetMD5(string str)
  224. {
  225. return GetMD5(str, Encoding.UTF8);
  226. }
  227. public static string GetMD5(string str, Encoding ed)
  228. {
  229. byte[] data = ed.GetBytes(str);
  230. data = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
  231. string ret = "";
  232. for (int i = 0; i < data.Length; i++)
  233. {
  234. ret += data[i].ToString("x1").PadLeft(2, '0');//ToString("x1"):转换为16进制
  235. }
  236. return ret;
  237. }
  238. /// <summary>
  239. /// 获取MD5串(未转大小写)
  240. /// </summary>
  241. public static string GetMD5(byte[] data)
  242. {
  243. data = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
  244. string ret = "";
  245. for (int i = 0; i < data.Length; i++)
  246. {
  247. ret += data[i].ToString("x1").PadLeft(2, '0');//ToString("x1"):转换为16进制
  248. }
  249. return ret;
  250. }
  251. /// <summary>
  252. /// MD5 16位加密
  253. /// </summary>
  254. /// <param name="ConvertString"></param>
  255. /// <returns></returns>
  256. public static string GetMd5_16bit(string data)
  257. {
  258. System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  259. string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(data)), 4, 8);
  260. t2 = t2.Replace("-", "");
  261. return t2;
  262. }
  263. public static string GetMd5_16bit(byte[] data)
  264. {
  265. System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  266. string t2 = BitConverter.ToString(md5.ComputeHash(data), 4, 8);
  267. t2 = t2.Replace("-", "");
  268. return t2;
  269. }
  270. public static string subString(string text, int leftLen)
  271. {
  272. if (text == null || text.Length < leftLen)
  273. return text;
  274. return text.Substring(0, leftLen) + "...";
  275. }
  276. //cpu序列号
  277. //获取计算机其它信息
  278. public static string GetPCOtherInfo()
  279. {
  280. string lsInfo;
  281. string lsName = System.Net.Dns.GetHostName();
  282. lsInfo = "计算机名称:" + lsName + " ";
  283. // 获得本机局域网IP地址
  284. System.Net.IPAddress addr = new System.Net.IPAddress(System.Net.Dns.GetHostByName(lsName).AddressList[0].Address);
  285. lsInfo += "局域网内IP地址:" + addr.ToString();
  286. //
  287. return lsInfo;
  288. }
  289. /// <summary>
  290. /// 模糊匹配字符串
  291. /// </summary>
  292. /// <param name="fullValue"></param>
  293. /// <param name="allKeys"></param>
  294. /// <param name="matchCase"></param>
  295. /// <param name="mustFirst"></param>
  296. /// <returns></returns>
  297. public static bool find_Fuzzy(string fullValue, List<string> allKeys, bool matchCase = true, bool mustFirst = true)
  298. {
  299. if (!matchCase)
  300. fullValue = fullValue.ToLower();
  301. string keyName = "";
  302. allKeys.ForEach(key => {
  303. int index = fullValue.IndexOf(matchCase ? key : key.ToLower());
  304. if (index > -1)
  305. {
  306. if (mustFirst)
  307. {
  308. if (index == 0)
  309. {
  310. keyName = key;
  311. return;
  312. }
  313. }
  314. else
  315. {
  316. keyName = key;
  317. return;
  318. }
  319. }
  320. });
  321. return keyName != "";
  322. }
  323. public static JObject getPropertys(Object o, string[] skipPropertys)
  324. {
  325. JObject data = new JObject();
  326. Type t = o.GetType();//获得该类的Type
  327. //再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
  328. foreach (PropertyInfo pi in t.GetProperties())
  329. {
  330. object value1 = pi.GetValue(o, null);//用pi.GetValue获得值
  331. string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
  332. //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
  333. if (value1 == null)
  334. {
  335. data.Add(name, null);
  336. }
  337. else
  338. {
  339. Type type = value1.GetType();
  340. if (type == typeof(string) || type == typeof(int) || type == typeof(float) || type == typeof(double) || type == typeof(decimal))
  341. {
  342. data.Add(name, value1.ToString());
  343. }
  344. }
  345. }
  346. return data;
  347. }
  348. /// <summary>
  349. /// 获取文件对应MIME类型
  350. /// </summary>
  351. /// <param name="fileExtention">文件扩展名,如.jpg</param>
  352. /// <returns></returns>
  353. public static string GetContentType(string fileExtention)
  354. {
  355. if (string.Compare(fileExtention, ".html", true) == 0 || string.Compare(fileExtention, ".htm", true) == 0)
  356. return "text/html;charset=utf-8";
  357. else if (string.Compare(fileExtention, ".js", true) == 0)
  358. return "application/javascript";
  359. else if (string.Compare(fileExtention, ".css", true) == 0)
  360. return "text/css";
  361. else if (string.Compare(fileExtention, ".png", true) == 0)
  362. return "image/png";
  363. else if (string.Compare(fileExtention, ".jpg", true) == 0 || string.Compare(fileExtention, ".jpeg", true) == 0)
  364. return "image/jpeg";
  365. else if (string.Compare(fileExtention, ".gif", true) == 0)
  366. return "image/gif";
  367. else if (string.Compare(fileExtention, ".swf", true) == 0)
  368. return "application/x-shockwave-flash";
  369. else if (string.Compare(fileExtention, ".bcmap", true) == 0)
  370. return "image/svg+xml";
  371. else if (string.Compare(fileExtention, ".properties", true) == 0)
  372. return "application/octet-stream";
  373. else if (string.Compare(fileExtention, ".map", true) == 0)
  374. return "text/plain";
  375. else if (string.Compare(fileExtention, ".svg", true) == 0)
  376. return "image/svg+xml";
  377. else if (string.Compare(fileExtention, ".pdf", true) == 0)
  378. return "application/pdf";
  379. else if (string.Compare(fileExtention, ".txt", true) == 0)
  380. return "text/*";
  381. else if (string.Compare(fileExtention, ".dat", true) == 0)
  382. return "text/*";
  383. else
  384. return "application/octet-stream";//application/octet-stream
  385. }
  386. /// <summary>
  387. /// mm转像素
  388. /// </summary>
  389. /// <param name="mm"></param>
  390. /// <param name="dpi">PDF=72(默认) 显示器=96</param>
  391. /// <returns></returns>
  392. public static int mm2px(float mm, int dpi = 72)
  393. {
  394. return (int)((dpi / 25.4f) * mm);
  395. }
  396. /// <summary>
  397. /// 像素转mm
  398. /// </summary>
  399. /// <param name="px"></param>
  400. /// <param name="dpi">PDF=72(默认) 显示器=96</param>
  401. /// <returns></returns>
  402. public static float px2mm(int px, int dpi = 72)
  403. {
  404. return px / (dpi / 25.4f);
  405. }
  406. public static void addKey(JObject obj, string key, JToken value)
  407. {
  408. if (obj.ContainsKey(key))
  409. obj[key] = value;
  410. else
  411. obj.Add(key, value);
  412. }
  413. /// <summary>
  414. /// IO二进制数据格式化到8位 XXXX10X0
  415. /// </summary>
  416. /// <param name="datas"></param>
  417. /// <returns></returns>
  418. public static string[] IODataFormatBinaryStr(string[] datas, bool clone,char defaultPadChar='X')
  419. {
  420. string[] datas2= new string[datas.Length];
  421. for(int i = 0;i < datas.Length; i++)
  422. {
  423. if (clone)
  424. {
  425. datas2[i] = datas[i].Replace(" ", "");
  426. if (datas2[i].Length > 8)
  427. datas2[i] = datas2[i].Substring(datas2[i].Length - 8);
  428. else if (datas2[i].Length < 8)
  429. datas2[i] = datas2[i].PadLeft(8, defaultPadChar);
  430. }
  431. else
  432. {
  433. datas[i] = datas[i].Replace(" ", "");
  434. if (datas[i].Length > 8)
  435. datas[i] = datas[i].Substring(datas[i].Length - 8);
  436. else if (datas[i].Length < 8)
  437. datas[i] = datas[i].PadLeft(8, defaultPadChar);
  438. datas2 = datas;
  439. }
  440. }
  441. return datas2;
  442. }
  443. public static byte[] IOFormatBinary2bytes(string[] datas)
  444. {
  445. byte[] result=new byte[datas.Length];
  446. string str;
  447. for (int i = 0; i < datas.Length; i++)
  448. {
  449. str = "";
  450. datas[i] = datas[i].Replace(" ", "");
  451. for (int j = 0; j < datas[i].Length; j++)
  452. {
  453. if (datas[i][j] == '1' || datas[i][j] == 'H')
  454. str += "1";
  455. else
  456. str += "0";
  457. }
  458. result[i] = Convert.ToByte(str, 2);
  459. }
  460. return result;
  461. }
  462. public static void showRowNum_onDataGrid_RowPostPaint(DataGridView dgv, object sender, DataGridViewRowPostPaintEventArgs e)
  463. {
  464. Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);
  465. TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, rectangle, dgv.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
  466. }
  467. /// <summary>
  468. ///
  469. /// </summary>
  470. /// <param name="op_show_list">[XXHL XXXX,XXXX XXXX,...]</param>
  471. /// <param name="currIoDatas">[byte,byte,byte,byte]</param>
  472. /// <returns></returns>
  473. public static bool compareIOInput(string[] op_show_list, byte[] currIoDatas)
  474. {
  475. int isok = 0;//1-true 2-false
  476. string IN_OP_SHOW;
  477. for (int i = 0; i < currIoDatas.Length; i++)
  478. {
  479. IN_OP_SHOW = op_show_list[i].Replace(" ", "").PadLeft(8, 'X');
  480. if (IN_OP_SHOW.IndexOf('H') < 0 && IN_OP_SHOW.IndexOf('L') < 0)
  481. continue;
  482. for (int j = 7; j >= 0; j--)
  483. {
  484. byte bit = (byte)(1 << 7 - j);
  485. if (IN_OP_SHOW[j] == 'H')
  486. {
  487. if ((bit & currIoDatas[i]) > 0)
  488. isok = 1;
  489. else
  490. {
  491. isok = 2;
  492. break;
  493. }
  494. }
  495. else if (IN_OP_SHOW[j] == 'L')
  496. {
  497. if ((currIoDatas[i] ^ (currIoDatas[i] | bit)) > 0)
  498. isok = 1;
  499. else
  500. {
  501. isok = 2;
  502. break;
  503. }
  504. }
  505. }
  506. //已经不符
  507. if (isok == 2) break;
  508. }
  509. //
  510. return isok == 1;
  511. }
  512. public static string createSubDir(string basePath,List<string> subDirNames)
  513. {
  514. string path = basePath.Trim().Trim('\\')+"\\";
  515. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  516. foreach(string subDir in subDirNames)
  517. {
  518. path += subDir + "\\";
  519. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  520. }
  521. return path;
  522. }
  523. }
  524. }