版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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 ProductionControl.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. /// <summary>
  84. /// 浮点 (可以带正负号)
  85. /// </summary>
  86. /// <param name="inputData"></param>
  87. /// <returns></returns>
  88. public static bool IsDecimal(string inputData)
  89. {
  90. Match m = RegDecimal.Match(inputData);
  91. return m.Success;
  92. }
  93. public static string file2Base64(string filePath)
  94. {
  95. return Convert.ToBase64String(File.ReadAllBytes(filePath));
  96. }
  97. /// <summary>
  98. /// 结构体转byte数组
  99. /// </summary>
  100. /// <param name="structObj">要转换的结构体</param>
  101. /// <returns>转换后的byte数组</returns>
  102. public static byte[] StructToBytes(object structObj)
  103. {
  104. int size = Marshal.SizeOf(structObj);
  105. IntPtr buffer = Marshal.AllocHGlobal(size);
  106. try
  107. {
  108. Marshal.StructureToPtr(structObj, buffer, false);
  109. byte[] bytes = new byte[size];
  110. Marshal.Copy(buffer, bytes, 0, size);
  111. return bytes;
  112. }
  113. finally
  114. {
  115. Marshal.FreeHGlobal(buffer);
  116. }
  117. }
  118. /// <summary>
  119. /// byte数组转结构体
  120. /// </summary>
  121. /// <param name="bytes">byte数组</param>
  122. /// <param name="type">结构体类型</param>
  123. /// <returns>转换后的结构体</returns>
  124. public static object BytesToStruct(byte[] bytes, Type strcutType)
  125. {
  126. int size = Marshal.SizeOf(strcutType);
  127. IntPtr buffer = Marshal.AllocHGlobal(size);
  128. try
  129. {
  130. Marshal.Copy(bytes, 0, buffer, size);
  131. return Marshal.PtrToStructure(buffer, strcutType);
  132. }
  133. finally
  134. {
  135. Marshal.FreeHGlobal(buffer);
  136. }
  137. }
  138. /// <summary>
  139. /// 是否为系统不可操作窗体(如桌面、任务栏等)
  140. /// </summary>
  141. /// <returns></returns>
  142. public static bool IsSysWin(IntPtr WinHwnd)
  143. {
  144. if (WinHwnd != IntPtr.Zero)
  145. {
  146. StringBuilder lsbClassName = new StringBuilder(256);
  147. API.GetClassName(WinHwnd, lsbClassName, 256 - 1);
  148. string lsWinClassName = lsbClassName.ToString().ToLower();
  149. return (lsWinClassName == "progman" || lsWinClassName == "shell_traywnd");
  150. }
  151. return false;
  152. }
  153. public static bool DisableDevice(string sDeviceID)
  154. {
  155. try
  156. {
  157. if (sDeviceID == null || sDeviceID.Trim() == "" || !System.IO.File.Exists(System.Environment.SystemDirectory + "\\devcon.exe"))
  158. return false;
  159. string[] lsDeviceIDs = sDeviceID.Split(new char[] { ';', ',' });
  160. ProcessStartInfo info;
  161. for (int i = 0; i < lsDeviceIDs.Length; i++)
  162. {
  163. if (lsDeviceIDs[i].Trim() == "") continue;
  164. info = new ProcessStartInfo();
  165. info.FileName = System.Environment.SystemDirectory + "\\devcon.exe"; // 要启动的程序
  166. info.Arguments = "disable " + lsDeviceIDs[i]; //传递给程序的参数
  167. info.WindowStyle = ProcessWindowStyle.Hidden; //隐藏窗口
  168. Process pro = Process.Start(info); //启动程序
  169. }
  170. return true;
  171. }
  172. catch
  173. {
  174. return false;
  175. }
  176. }
  177. public static bool EnableDevice(string sDeviceID)
  178. {
  179. try
  180. {
  181. if (sDeviceID == null || sDeviceID.Trim() == "" || !System.IO.File.Exists(System.Environment.SystemDirectory + "\\devcon.exe"))
  182. return false;
  183. string[] lsDeviceIDs = sDeviceID.Split(new char[] { ';' });
  184. ProcessStartInfo info;
  185. for (int i = 0; i < lsDeviceIDs.Length; i++)
  186. {
  187. if (lsDeviceIDs[i].Trim() == "") continue;
  188. info = new ProcessStartInfo();
  189. info.FileName = System.Environment.SystemDirectory + "\\devcon.exe"; // 要启动的程序
  190. info.Arguments = "enable " + lsDeviceIDs[i]; //传递给程序的参数
  191. info.WindowStyle = ProcessWindowStyle.Hidden; //隐藏窗口
  192. Process pro = Process.Start(info); //启动程序
  193. }
  194. return true;
  195. }
  196. catch
  197. {
  198. return false;
  199. }
  200. }
  201. /// <summary>
  202. /// 获取时间戳
  203. /// </summary>
  204. public static string GetTimestamp()
  205. {
  206. DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  207. DateTime dtNow = DateTime.Now;
  208. TimeSpan toNow = dtNow.Subtract(dtStart);
  209. System.Random rand = new Random();
  210. string timeStamp = toNow.Ticks.ToString() + rand.Next(9);
  211. return timeStamp;
  212. }
  213. /// <summary>
  214. /// 获取MD5串(未转大小写)
  215. /// </summary>
  216. public static string GetMD5(string str)
  217. {
  218. return GetMD5(str, Encoding.UTF8);
  219. }
  220. public static string GetMD5(string str, Encoding ed)
  221. {
  222. byte[] data = ed.GetBytes(str);
  223. data = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
  224. string ret = "";
  225. for (int i = 0; i < data.Length; i++)
  226. {
  227. ret += data[i].ToString("x1").PadLeft(2, '0');//ToString("x1"):转换为16进制
  228. }
  229. return ret;
  230. }
  231. /// <summary>
  232. /// 获取MD5串(未转大小写)
  233. /// </summary>
  234. public static string GetMD5(byte[] data)
  235. {
  236. data = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(data);
  237. string ret = "";
  238. for (int i = 0; i < data.Length; i++)
  239. {
  240. ret += data[i].ToString("x1").PadLeft(2, '0');//ToString("x1"):转换为16进制
  241. }
  242. return ret;
  243. }
  244. /// <summary>
  245. /// MD5 16位加密
  246. /// </summary>
  247. /// <param name="ConvertString"></param>
  248. /// <returns></returns>
  249. public static string GetMd5_16bit(string data)
  250. {
  251. System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  252. string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(data)), 4, 8);
  253. t2 = t2.Replace("-", "");
  254. return t2;
  255. }
  256. public static string GetMd5_16bit(byte[] data)
  257. {
  258. System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  259. string t2 = BitConverter.ToString(md5.ComputeHash(data), 4, 8);
  260. t2 = t2.Replace("-", "");
  261. return t2;
  262. }
  263. public static string subString(string text, int leftLen)
  264. {
  265. if (text == null || text.Length < leftLen)
  266. return text;
  267. return text.Substring(0, leftLen) + "...";
  268. }
  269. public static string GetHardwareIDHashCode()
  270. {
  271. string lsID = GetCpuID() + GetHDID() + GetMacID();
  272. return lsID;
  273. }
  274. //cpu序列号
  275. private static string GetCpuID()
  276. {
  277. try
  278. {
  279. string cpuInfo = "";
  280. ManagementClass cimobject = new ManagementClass("Win32_Processor");
  281. ManagementObjectCollection moc = cimobject.GetInstances();
  282. foreach (ManagementObject mo in moc)
  283. {
  284. cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
  285. //label1.Text += "cpu序列号:" + cpuInfo.ToString() + "\n";
  286. }
  287. return cpuInfo;
  288. }
  289. catch { return ""; }
  290. }
  291. //获取硬盘ID
  292. private static string GetHDID()
  293. {
  294. try
  295. {
  296. string HDid = "";
  297. ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
  298. ManagementObjectCollection moc1 = cimobject1.GetInstances();
  299. foreach (ManagementObject mo in moc1)
  300. {
  301. HDid = (string)mo.Properties["Model"].Value;
  302. //label1.Text += "硬盘序列号:" + HDid.ToString() + "\n";
  303. }
  304. return HDid;
  305. }
  306. catch { return ""; }
  307. }
  308. //获取网卡硬件MAC地址
  309. private static string GetMacID()
  310. {
  311. try
  312. {
  313. string Mac1 = "";
  314. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  315. ManagementObjectCollection moc2 = mc.GetInstances();
  316. foreach (ManagementObject mo in moc2)
  317. {
  318. if ((bool)mo["IPEnabled"] == true)
  319. {
  320. Mac1 = mo["MacAddress"].ToString();
  321. //label1.Text += "MAC address\t{0}" + Mac1 + "\n";
  322. mo.Dispose();
  323. break;
  324. }
  325. mo.Dispose();
  326. }
  327. return Mac1;
  328. }
  329. catch { return ""; }
  330. }
  331. //获取计算机其它信息
  332. public static string GetPCOtherInfo()
  333. {
  334. string lsInfo;
  335. string lsName = System.Net.Dns.GetHostName();
  336. lsInfo = "计算机名称:" + lsName + " ";
  337. // 获得本机局域网IP地址
  338. System.Net.IPAddress addr = new System.Net.IPAddress(System.Net.Dns.GetHostByName(lsName).AddressList[0].Address);
  339. lsInfo += "局域网内IP地址:" + addr.ToString();
  340. //
  341. return lsInfo;
  342. }
  343. /// <summary>
  344. /// 模糊匹配字符串
  345. /// </summary>
  346. /// <param name="fullValue"></param>
  347. /// <param name="allKeys"></param>
  348. /// <param name="matchCase"></param>
  349. /// <param name="mustFirst"></param>
  350. /// <returns></returns>
  351. public static bool find_Fuzzy(string fullValue, List<string> allKeys, bool matchCase = true, bool mustFirst = true)
  352. {
  353. if (!matchCase)
  354. fullValue = fullValue.ToLower();
  355. string keyName = "";
  356. allKeys.ForEach(key => {
  357. int index = fullValue.IndexOf(matchCase ? key : key.ToLower());
  358. if (index > -1)
  359. {
  360. if (mustFirst)
  361. {
  362. if (index == 0)
  363. {
  364. keyName = key;
  365. return;
  366. }
  367. }
  368. else
  369. {
  370. keyName = key;
  371. return;
  372. }
  373. }
  374. });
  375. return keyName != "";
  376. }
  377. public static JObject getPropertys(Object o, string[] skipPropertys)
  378. {
  379. JObject data = new JObject();
  380. Type t = o.GetType();//获得该类的Type
  381. //再用Type.GetProperties获得PropertyInfo[],然后就可以用foreach 遍历了
  382. foreach (PropertyInfo pi in t.GetProperties())
  383. {
  384. object value1 = pi.GetValue(o, null);//用pi.GetValue获得值
  385. string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作
  386. //获得属性的类型,进行判断然后进行以后的操作,例如判断获得的属性是整数
  387. if (value1 == null)
  388. {
  389. data.Add(name, null);
  390. }
  391. else
  392. {
  393. Type type = value1.GetType();
  394. if (type == typeof(string) || type == typeof(int) || type == typeof(float) || type == typeof(double) || type == typeof(decimal))
  395. {
  396. data.Add(name, value1.ToString());
  397. }
  398. }
  399. }
  400. return data;
  401. }
  402. /// <summary>
  403. /// 获取文件对应MIME类型
  404. /// </summary>
  405. /// <param name="fileExtention">文件扩展名,如.jpg</param>
  406. /// <returns></returns>
  407. public static string GetContentType(string fileExtention)
  408. {
  409. if (string.Compare(fileExtention, ".html", true) == 0 || string.Compare(fileExtention, ".htm", true) == 0)
  410. return "text/html;charset=utf-8";
  411. else if (string.Compare(fileExtention, ".js", true) == 0)
  412. return "application/javascript";
  413. else if (string.Compare(fileExtention, ".css", true) == 0)
  414. return "text/css";
  415. else if (string.Compare(fileExtention, ".png", true) == 0)
  416. return "image/png";
  417. else if (string.Compare(fileExtention, ".jpg", true) == 0 || string.Compare(fileExtention, ".jpeg", true) == 0)
  418. return "image/jpeg";
  419. else if (string.Compare(fileExtention, ".gif", true) == 0)
  420. return "image/gif";
  421. else if (string.Compare(fileExtention, ".swf", true) == 0)
  422. return "application/x-shockwave-flash";
  423. else if (string.Compare(fileExtention, ".bcmap", true) == 0)
  424. return "image/svg+xml";
  425. else if (string.Compare(fileExtention, ".properties", true) == 0)
  426. return "application/octet-stream";
  427. else if (string.Compare(fileExtention, ".map", true) == 0)
  428. return "text/plain";
  429. else if (string.Compare(fileExtention, ".svg", true) == 0)
  430. return "image/svg+xml";
  431. else if (string.Compare(fileExtention, ".pdf", true) == 0)
  432. return "application/pdf";
  433. else if (string.Compare(fileExtention, ".txt", true) == 0)
  434. return "text/*";
  435. else if (string.Compare(fileExtention, ".dat", true) == 0)
  436. return "text/*";
  437. else
  438. return "application/octet-stream";//application/octet-stream
  439. }
  440. /// <summary>
  441. /// mm转像素
  442. /// </summary>
  443. /// <param name="mm"></param>
  444. /// <param name="dpi">PDF=72(默认) 显示器=96</param>
  445. /// <returns></returns>
  446. public static int mm2px(float mm, int dpi = 72)
  447. {
  448. return (int)((dpi / 25.4f) * mm);
  449. }
  450. /// <summary>
  451. /// 像素转mm
  452. /// </summary>
  453. /// <param name="px"></param>
  454. /// <param name="dpi">PDF=72(默认) 显示器=96</param>
  455. /// <returns></returns>
  456. public static float px2mm(int px, int dpi = 72)
  457. {
  458. return px / (dpi / 25.4f);
  459. }
  460. public static void addKey(JObject obj, string key, JToken value)
  461. {
  462. if (obj.ContainsKey(key))
  463. obj[key] = value;
  464. else
  465. obj.Add(key, value);
  466. }
  467. /// <summary>
  468. /// IO二进制数据格式化到8位 XXXX10X0
  469. /// </summary>
  470. /// <param name="datas"></param>
  471. /// <returns></returns>
  472. public static string[] IODataFormatBinaryStr(string[] datas, bool clone,char defaultPadChar='X')
  473. {
  474. string[] datas2= new string[datas.Length];
  475. for(int i = 0;i < datas.Length; i++)
  476. {
  477. if (clone)
  478. {
  479. datas2[i] = datas[i].Replace(" ", "");
  480. if (datas2[i].Length > 8)
  481. datas2[i] = datas2[i].Substring(datas2[i].Length - 8);
  482. else if (datas2[i].Length < 8)
  483. datas2[i] = datas2[i].PadLeft(8, defaultPadChar);
  484. }
  485. else
  486. {
  487. datas[i] = datas[i].Replace(" ", "");
  488. if (datas[i].Length > 8)
  489. datas[i] = datas[i].Substring(datas[i].Length - 8);
  490. else if (datas[i].Length < 8)
  491. datas[i] = datas[i].PadLeft(8, defaultPadChar);
  492. datas2 = datas;
  493. }
  494. }
  495. return datas2;
  496. }
  497. public static byte[] IOFormatBinary2bytes(string[] datas)
  498. {
  499. byte[] result=new byte[datas.Length];
  500. string str;
  501. for (int i = 0; i < datas.Length; i++)
  502. {
  503. str = "";
  504. datas[i] = datas[i].Replace(" ", "");
  505. for (int j = 0; j < datas[i].Length; j++)
  506. {
  507. if (datas[i][j] == '1' || datas[i][j] == 'H')
  508. str += "1";
  509. else
  510. str += "0";
  511. }
  512. result[i] = Convert.ToByte(str, 2);
  513. }
  514. return result;
  515. }
  516. public static void showRowNum_onDataGrid_RowPostPaint(DataGridView dgv, object sender, DataGridViewRowPostPaintEventArgs e)
  517. {
  518. Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);
  519. TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, rectangle, dgv.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
  520. }
  521. /// <summary>
  522. ///
  523. /// </summary>
  524. /// <param name="op_show_list">[XXHL XXXX,XXXX XXXX,...]</param>
  525. /// <param name="currIoDatas">[byte,byte,byte,byte]</param>
  526. /// <returns></returns>
  527. public static bool compareIOInput(string[] op_show_list, byte[] currIoDatas)
  528. {
  529. int isok = 0;//1-true 2-false
  530. string IN_OP_SHOW;
  531. for (int i = 0; i < currIoDatas.Length; i++)
  532. {
  533. IN_OP_SHOW = op_show_list[i].Replace(" ", "").PadLeft(8, 'X');
  534. if (IN_OP_SHOW.IndexOf('H') < 0 && IN_OP_SHOW.IndexOf('L') < 0)
  535. continue;
  536. for (int j = 7; j >= 0; j--)
  537. {
  538. byte bit = (byte)(1 << 7 - j);
  539. if (IN_OP_SHOW[j] == 'H')
  540. {
  541. if ((bit & currIoDatas[i]) > 0)
  542. isok = 1;
  543. else
  544. {
  545. isok = 2;
  546. break;
  547. }
  548. }
  549. else if (IN_OP_SHOW[j] == 'L')
  550. {
  551. if ((currIoDatas[i] ^ (currIoDatas[i] | bit)) > 0)
  552. isok = 1;
  553. else
  554. {
  555. isok = 2;
  556. break;
  557. }
  558. }
  559. }
  560. //已经不符
  561. if (isok == 2) break;
  562. }
  563. //
  564. return isok == 1;
  565. }
  566. public static string createSubDir(string basePath,List<string> subDirNames)
  567. {
  568. string path = basePath.Trim().Trim('\\')+"\\";
  569. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  570. foreach(string subDir in subDirNames)
  571. {
  572. path += subDir + "\\";
  573. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  574. }
  575. return path;
  576. }
  577. }
  578. }