版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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