BaseUtil.cs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773
  1. using LabelManager2;
  2. using Microsoft.Win32;
  3. using NPOI.SS.Formula.Functions;
  4. using Seagull.BarTender.Print;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.ComponentModel;
  9. using System.Data;
  10. using System.Diagnostics;
  11. using System.Drawing;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Net.Sockets;
  16. using System.Reflection;
  17. using System.Text;
  18. using System.Text.RegularExpressions;
  19. using System.Threading;
  20. using System.Windows.Forms;
  21. using System.Windows.Forms.DataVisualization.Charting;
  22. using System.Xml;
  23. using UAS_MES_NEW.CustomControl.DataGrid_View;
  24. using UAS_MES_NEW.CustomControl.GroupBoxWithBorder;
  25. using UAS_MES_NEW.CustomControl.TextBoxWithIcon;
  26. using UAS_MES_NEW.CustomControl.ValueLabel;
  27. using UAS_MES_NEW.Entity;
  28. using static System.Windows.Forms.Control;
  29. namespace UAS_MES_NEW.PublicMethod
  30. {
  31. class BaseUtil
  32. {
  33. /// <summary>
  34. /// 检测TCP连接是否存在还是已经中断
  35. /// </summary>
  36. /// <param name="c"></param>
  37. /// <returns></returns>
  38. public static bool IsOnline(TcpClient c)
  39. {
  40. return !((c.Client.Poll(1000, SelectMode.SelectRead) && (c.Client.Available == 0)) || !c.Client.Connected);
  41. }
  42. public static Control GetControl(Control ctl, string Name)
  43. {
  44. if (ctl.Name == Name)
  45. return ctl;
  46. else
  47. return GetControl(ctl.Parent, Name);
  48. }
  49. public static string DToAny(double DB, int Type)
  50. {
  51. string H = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  52. string H1 = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
  53. long D;
  54. double B;
  55. string tempD = "", tempB = "";
  56. if (Type == 32)
  57. {
  58. return GetRandomChar(H1);
  59. }
  60. else
  61. {
  62. D = (long)DB;
  63. B = DB - D;
  64. if (D == 0)
  65. {
  66. tempD = "0";
  67. }
  68. while (D != 0)
  69. {
  70. tempD = H[(((int)D % Type))] + tempD;
  71. D = D / Type;
  72. }
  73. for (int i = 0; i < 7; i++)
  74. {
  75. if (B == 0)
  76. {
  77. break;
  78. }
  79. tempB += H[((int)(B * Type))];
  80. B = B * Type - (int)(B * Type);
  81. }
  82. if (tempB == "")
  83. {
  84. return tempD;
  85. }
  86. else
  87. {
  88. return tempD + "." + tempB;
  89. }
  90. }
  91. }
  92. public static string DToAny(double DB, int Type, string char_out)
  93. {
  94. string H = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  95. long D;
  96. double B;
  97. string tempD = "", tempB = "";
  98. for (int i = 0; i < char_out.Length; i++)
  99. {
  100. H = H.Replace(char_out[i].ToString(), "");
  101. }
  102. if (Type != H.Length && Type != 10 && Type != 16)
  103. {
  104. ShowError("字符长度截取错误,请检查进制和去除字符");
  105. return "";
  106. }
  107. D = (long)DB;
  108. B = DB - D;
  109. if (D == 0)
  110. {
  111. tempD = "0";
  112. }
  113. while (D != 0)
  114. {
  115. tempD = H[(((int)D % Type))] + tempD;
  116. D = D / Type;
  117. }
  118. for (int i = 0; i < 7; i++)
  119. {
  120. if (B == 0)
  121. {
  122. break;
  123. }
  124. tempB += H[((int)(B * Type))];
  125. B = B * Type - (int)(B * Type);
  126. }
  127. if (tempB == "")
  128. {
  129. return tempD;
  130. }
  131. else
  132. {
  133. return tempD + "." + tempB;
  134. }
  135. }
  136. public static string GetRandomChar(string str)
  137. {
  138. byte[] buffer = Guid.NewGuid().ToByteArray();
  139. int iSeed = BitConverter.ToInt32(buffer, 0);
  140. Random random = new Random(iSeed);
  141. string data = "";
  142. for (int i = 0; i < 5; i++)
  143. {
  144. int index = random.Next(0, 31);
  145. data += str[index];
  146. }
  147. return data;
  148. }
  149. /// <summary>
  150. /// 通过DataTable的ColumnName和Caption来拼接一条语句
  151. /// </summary>
  152. /// <param name=""></param>
  153. /// <returns></returns>
  154. public static string GetGridViewSelectContent(DataGridView d)
  155. {
  156. StringBuilder selectConetnt = new StringBuilder();
  157. DataTable dt = (DataTable)d.DataSource;
  158. if (dt == null)
  159. {
  160. foreach (DataGridViewColumn dc in d.Columns)
  161. {
  162. if (dc.DataPropertyName != "" && dc.DataPropertyName != null)
  163. {
  164. selectConetnt.Append(dc.Name + " as " + dc.Name + ",");
  165. }
  166. }
  167. }
  168. else
  169. {
  170. foreach (DataColumn dc in dt.Columns)
  171. {
  172. selectConetnt.Append(dc.Caption + " as " + dc.ColumnName + ",");
  173. }
  174. }
  175. return selectConetnt.Remove(selectConetnt.Length - 1, 1).ToString();
  176. }
  177. /// <summary>
  178. /// 禁止DataGirdView排序
  179. /// </summary>
  180. /// <param name="Dgv"></param>
  181. public static void DataGridViewNotSort(DataGridView Dgv)
  182. {
  183. foreach (DataGridViewColumn item in Dgv.Columns)
  184. item.SortMode = DataGridViewColumnSortMode.NotSortable;
  185. }
  186. public static string GetLocalIP()
  187. {
  188. try
  189. {
  190. string HostName = Dns.GetHostName(); //得到主机名
  191. IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
  192. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  193. {
  194. //从IP地址列表中筛选出IPv4类型的IP地址
  195. //AddressFamily.InterNetwork表示此IP为IPv4,
  196. //AddressFamily.InterNetworkV6表示此地址为IPv6类型
  197. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  198. {
  199. return IpEntry.AddressList[i].ToString();
  200. }
  201. }
  202. return "";
  203. }
  204. catch (Exception ex)
  205. {
  206. MessageBox.Show("获取本机IP出错:" + ex.Message);
  207. return "";
  208. }
  209. }
  210. /// <summary>
  211. /// 通过字段和其展示的中文值获取查询的内容
  212. /// </summary>
  213. /// <param name="field"></param>
  214. /// <param name="cnfield"></param>
  215. /// <returns></returns>
  216. public static string GetSelectContentByStringArray(string[] field, string[] cnfield)
  217. {
  218. StringBuilder sb = new StringBuilder();
  219. for (int i = 0; i < field.Length; i++)
  220. {
  221. sb.Append(field[i] + " as " + cnfield[i] + ",");
  222. }
  223. //去掉多余的逗号
  224. sb.Remove(sb.Length - 1, 1);
  225. return sb.ToString();
  226. }
  227. static int SortByIndex(Control A, Control B)
  228. {
  229. return A.TabIndex.CompareTo(B.TabIndex);
  230. }
  231. public static bool CheckBarTenderEnable()
  232. {
  233. var reg = new string[] {
  234. @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
  235. @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
  236. };
  237. string tempType = null;
  238. int softNum = 0;//所有已经安装的程序数量
  239. RegistryKey currentKey = null;
  240. var ls = new List<Dictionary<string, string>>();
  241. foreach (var item222 in reg)
  242. {
  243. object displayName = null, uninstallString = null, installLocation = null, releaseType = null;
  244. RegistryKey pregkey = Registry.LocalMachine.OpenSubKey(item222);//获取指定路径下的键
  245. foreach (string item in pregkey.GetSubKeyNames()) //循环所有子键
  246. {
  247. currentKey = pregkey.OpenSubKey(item);
  248. displayName = currentKey.GetValue("DisplayName"); //获取显示名称
  249. installLocation = currentKey.GetValue("InstallLocation"); //获取安装路径
  250. uninstallString = currentKey.GetValue("UninstallString"); //获取卸载字符串路径
  251. releaseType = currentKey.GetValue("ReleaseType"); //发行类型,值是Security Update为安全更新,Update为更新
  252. bool isSecurityUpdate = false;
  253. if (releaseType != null)
  254. {
  255. tempType = releaseType.ToString();
  256. if (tempType == "Security Update" || tempType == "Update")
  257. {
  258. isSecurityUpdate = true;
  259. }
  260. }
  261. if (!isSecurityUpdate && displayName != null && uninstallString != null)
  262. {
  263. softNum++;
  264. if (displayName.ToString() == "BarTender 10.1")
  265. {
  266. return true;
  267. }
  268. }
  269. }
  270. }
  271. return false;
  272. }
  273. /// <summary>
  274. /// 传入控件的集合和DataTable,通过判断控件的名称和数据源的列的描述来匹配,支持单层的GroupBox和Panel
  275. /// </summary>
  276. /// <param name="collection"></param>
  277. /// <param name="dt"></param>
  278. public static void SetFormValue(ControlCollection collection, DataTable dt)
  279. {
  280. List<Control> ctl = new List<Control>();
  281. //将控件按照索引排序
  282. for (int i = 0; i < collection.Count; i++)
  283. {
  284. for (int j = 0; j < ctl.Count; j++)
  285. {
  286. if (!ctl.Contains(collection[i]))
  287. {
  288. if (collection[i].TabIndex > ctl[j].TabIndex)
  289. {
  290. ctl.Add(collection[i]);
  291. break;
  292. }
  293. else
  294. {
  295. ctl.Insert(j, collection[i]);
  296. break;
  297. }
  298. }
  299. }
  300. if (ctl.Count == 0)
  301. {
  302. ctl.Add(collection[i]);
  303. }
  304. }
  305. ctl.Sort(SortByIndex);
  306. //DataTable存在数据才进行赋值操作
  307. if (dt.Rows.Count > 0)
  308. {
  309. for (int i = 0; i < ctl.Count; i++)
  310. {
  311. //如果含有子控件则进行递归调用
  312. if (ctl[i].Controls.Count > 0)
  313. SetFormValue(ctl[i].Controls, dt);
  314. string controlName = ctl[i].Name;
  315. string controlsTag = ctl[i].Tag == null ? "" : ctl[i].Tag.ToString();
  316. //默认给TextBox和Label赋值
  317. if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox || ctl[i] is MaCodeSearchTextBox || ctl[i] is EnterTextBox || ctl[i] is TextBoxGeneratePaCode || ctl[i] is NumericUpDown || ctl[i] is TextBoxWithTextArea || ctl[i] is RichTextBox)
  318. {
  319. for (int j = 0; j < dt.Columns.Count; j++)
  320. {
  321. if (controlName.ToUpper() == dt.Columns[j].Caption.ToUpper() || controlsTag.ToUpper() == dt.Columns[j].Caption.ToUpper())
  322. {
  323. //字段含有Status内容的才进行转换
  324. if (controlName.ToUpper().Contains("STATUS") || controlsTag.ToUpper().Contains("STATUS"))
  325. {
  326. //对审批状态进行判断
  327. switch (dt.Rows[0][j].ToString().ToUpper())
  328. {
  329. case "ENTERING":
  330. ctl[i].Text = "在录入";
  331. break;
  332. case "UNAPPROVED":
  333. ctl[i].Text = "未批准";
  334. break;
  335. case "COMMITED":
  336. ctl[i].Text = "已提交";
  337. break;
  338. case "APPROVE":
  339. ctl[i].Text = "已批准";
  340. break;
  341. case "AUDITED":
  342. ctl[i].Text = "已审核";
  343. break;
  344. case "STARTED":
  345. ctl[i].Text = "已下放";
  346. break;
  347. case "UNCHECK":
  348. ctl[i].Text = "待检验";
  349. break;
  350. case "CHECKING":
  351. ctl[i].Text = "检验中";
  352. break;
  353. default:
  354. ctl[i].Text = dt.Rows[0][j].ToString();
  355. break;
  356. }
  357. }
  358. else
  359. ctl[i].Text = dt.Rows[0][j].ToString();
  360. }
  361. }
  362. }
  363. //对封装在GroupBox的和Panel的控件进行批量赋值
  364. if (ctl[i] is GroupBox || ctl[i] is Panel || ctl[i] is GroupBoxWithBorder)
  365. {
  366. for (int j = 0; j < ctl[i].Controls.Count; j++)
  367. {
  368. controlName = ctl[i].Controls[j].Name;
  369. if (ctl[i].Controls[j] is TextBox || ctl[i].Controls[j] is Label || ctl[i].Controls[j] is SearchTextBox || ctl[i].Controls[j] is MaCodeSearchTextBox)
  370. {
  371. for (int k = 0; k < dt.Columns.Count; k++)
  372. {
  373. if (controlName.ToUpper() == dt.Columns[k].Caption.ToUpper())
  374. {
  375. ctl[i].Controls[j].Text = dt.Rows[0][k].ToString();
  376. }
  377. }
  378. }
  379. }
  380. }
  381. }
  382. }
  383. //如果没有记录的话,将dt中含有的列的对应值设置为空
  384. else
  385. {
  386. for (int i = 0; i < ctl.Count; i++)
  387. {
  388. if (ctl[i] is TextBox || ctl[i] is Label || ctl[i] is SearchTextBox)
  389. {
  390. for (int j = 0; j < dt.Columns.Count; j++)
  391. {
  392. if (ctl[i].Name.ToUpper() == dt.Columns[j].Caption.ToUpper())
  393. {
  394. ctl[i].Text = "";
  395. }
  396. }
  397. }
  398. }
  399. }
  400. }
  401. /// <summary>
  402. /// 获取打印标签
  403. /// </summary>
  404. /// <param name="labelName"></param>
  405. /// <param name="labelUrl"></param>
  406. /// <param name="indate"></param>
  407. public static void GetPrintLabel(string labelName, string labelUrl)
  408. {
  409. BaseUtil.GetLabelUrl(labelUrl, labelName);
  410. }
  411. /// <summary>
  412. /// 获取打印标签
  413. /// </summary>
  414. /// <param name="labelName"></param>
  415. /// <param name="labelUrl"></param>
  416. /// <param name="indate"></param>
  417. public static void GetPrintLabel(string labelName, string labelUrl, string indate)
  418. {
  419. string LabelUrl = labelUrl;
  420. string LabelName = labelName;
  421. System.DateTime time = Convert.ToDateTime(indate);
  422. FileInfo file = new FileInfo(ftpOperater.DownLoadTo + LabelName);
  423. if (time.ToString() != file.LastWriteTime.ToString())
  424. BaseUtil.GetLabelUrl(LabelUrl, LabelName, time);
  425. }
  426. /// <summary>
  427. /// 获取标签的路径
  428. /// </summary>
  429. /// <param name="URL"></param>
  430. /// <param name="LabelName"></param>
  431. /// <param name="time"></param>
  432. /// <returns></returns>
  433. public static string GetLabelUrl(string URL, string LabelName, System.DateTime time)
  434. {
  435. ftpOperater ftp = new ftpOperater();
  436. return ftp.DownLoadFromSharePath(URL, LabelName);
  437. }
  438. /// <summary>
  439. /// 移除重复行
  440. /// </summary>
  441. /// <param name="dt"></param>
  442. /// <param name="field"></param>
  443. /// <returns></returns>
  444. public static DataTable DeleteSameRow(DataTable dt, string field)
  445. {
  446. ArrayList indexList = new ArrayList();
  447. // 找出待删除的行索引
  448. for (int i = 0; i < dt.Rows.Count - 1; i++)
  449. {
  450. if (!IsContain(indexList, i))
  451. {
  452. for (int j = i + 1; j < dt.Rows.Count; j++)
  453. {
  454. if (dt.Rows[i][field].ToString() == dt.Rows[j][field].ToString())
  455. {
  456. indexList.Add(j);
  457. }
  458. }
  459. }
  460. }
  461. indexList.Sort();
  462. // 排序
  463. for (int i = indexList.Count - 1; i >= 0; i--)// 根据待删除索引列表删除行
  464. {
  465. int index = Convert.ToInt32(indexList[i]);
  466. dt.Rows.RemoveAt(index);
  467. }
  468. return dt;
  469. }
  470. /// <summary>
  471. /// 判断数组中是否存在
  472. /// </summary>
  473. /// <param name="indexList">数组</param>
  474. /// <param name="index">索引</param>
  475. /// <returns></returns>
  476. public static bool IsContain(ArrayList indexList, int index)
  477. {
  478. for (int i = 0; i < indexList.Count; i++)
  479. {
  480. int tempIndex = Convert.ToInt32(indexList[i]);
  481. if (tempIndex == index)
  482. {
  483. return true;
  484. }
  485. }
  486. return false;
  487. }
  488. //播放音频文件
  489. public static void PlaySound(string FileName)
  490. {
  491. //要加载COM组件:Microsoft speech object Library
  492. if (!System.IO.File.Exists(FileName))
  493. {
  494. return;
  495. }
  496. SpeechLib.SpVoiceClass pp = new SpeechLib.SpVoiceClass();
  497. SpeechLib.SpFileStreamClass spFs = new SpeechLib.SpFileStreamClass();
  498. spFs.Open(FileName, SpeechLib.SpeechStreamFileMode.SSFMOpenForRead, true);
  499. SpeechLib.ISpeechBaseStream Istream = spFs as SpeechLib.ISpeechBaseStream;
  500. pp.SpeakStream(Istream, SpeechLib.SpeechVoiceSpeakFlags.SVSFIsFilename);
  501. spFs.Close();
  502. }
  503. /// <summary>
  504. /// 从DGV获取指定的列的数据形式是数组的形式
  505. /// </summary>
  506. public static ArrayList[] GetColumnDataFromDGV(DataGridView dgv, string[] ColumnName)
  507. {
  508. ArrayList[] array = new ArrayList[ColumnName.Length];
  509. //实例化和查询参数个数一样的ArrayList
  510. for (int i = 0; i < ColumnName.Length; i++)
  511. {
  512. array[i] = new ArrayList();
  513. }
  514. DataTable dt = (DataTable)dgv.DataSource;
  515. //如果第一列是否选框的话
  516. if (dgv.Columns[0] is DataGridViewCheckBoxColumn)
  517. {
  518. for (int i = 0; i < dt.Rows.Count; i++)
  519. {
  520. if (dgv.Rows[i].Cells[0].FormattedValue.ToString() == "True")
  521. {
  522. for (int j = 0; j < ColumnName.Length; j++)
  523. {
  524. array[j].Add(dt.Rows[i][ColumnName[j]]);
  525. }
  526. }
  527. }
  528. }
  529. //否则直接获取全部的数据
  530. else
  531. {
  532. for (int i = 0; i < dgv.RowCount; i++)
  533. {
  534. for (int j = 0; j < ColumnName.Length; j++)
  535. {
  536. array[j].Add(dt.Rows[i][ColumnName[j]]);
  537. }
  538. }
  539. }
  540. return array;
  541. }
  542. /// <summary>
  543. /// 通过DataGridView和需要隐藏的字段的数组来对字段进行隐藏
  544. /// </summary>
  545. /// <param name="dgv"></param>
  546. /// <param name="field"></param>
  547. public static void HideField(DataGridView dgv, string[] field)
  548. {
  549. DataTable dt = (DataTable)dgv.DataSource;
  550. foreach (DataColumn dc in dt.Columns)
  551. {
  552. foreach (string s in field)
  553. {
  554. if (dc.Caption == s)
  555. dgv.Columns[dc.ColumnName].Visible = false;
  556. }
  557. }
  558. }
  559. /// <summary>
  560. ///
  561. /// </summary>
  562. /// <param name="dgv"></param>
  563. public static void ExpandDGVCheck(DataGridViewExpand dgv, DataGridViewCellEventArgs e)
  564. {
  565. if (e.ColumnIndex == 0 && e.RowIndex >= 0)
  566. {
  567. if (dgv.Rows[e.RowIndex] is CollapseDataGridViewRow)
  568. {
  569. int CollapseRowCount = (dgv.Rows[e.RowIndex] as CollapseDataGridViewRow).Rows.Count;
  570. if (CollapseRowCount > 0)
  571. {
  572. for (int i = (e.RowIndex + 2); i < (e.RowIndex + 1 + CollapseRowCount); i++)
  573. {
  574. try
  575. {
  576. dgv.Rows[i].Cells[0].Value = dgv.Rows[e.RowIndex].Cells[0].EditedFormattedValue;
  577. }
  578. catch (Exception) { }
  579. }
  580. }
  581. }
  582. }
  583. }
  584. /// <summary>
  585. /// 通过查询的内容获取到字段的描述
  586. /// </summary>
  587. /// <param name="field"></param>
  588. /// <returns></returns>
  589. public static string[] GetCaptionFromField(string field)
  590. {
  591. string[] caption = field.Split(',');
  592. for (int i = 0; i < caption.Length; i++)
  593. {
  594. caption[i] = caption[i].Substring(0, caption[i].LastIndexOf("as")).Trim();
  595. }
  596. return caption;
  597. }
  598. /// <summary>
  599. /// 通过查询的语句获取查询的字段
  600. /// </summary>
  601. /// <param name="field"></param>
  602. /// <returns></returns>
  603. public static string[] GetField(string field)
  604. {
  605. string[] fields = field.Split(',');
  606. for (int i = 0; i < fields.Length; i++)
  607. {
  608. fields[i] = fields[i].Substring(fields[i].LastIndexOf("as") + 2, fields[i].Length - fields[i].LastIndexOf("as") - 2).Trim();
  609. }
  610. return fields;
  611. }
  612. /// <summary>
  613. /// 通过描述取DataTable的列名,主要用于从配置中取数据
  614. /// </summary>
  615. /// <param name="dt"></param>
  616. /// <param name="caption"></param>
  617. /// <returns></returns>
  618. public static string GetColumnNameByCaption(DataTable dt, string caption)
  619. {
  620. foreach (DataColumn dc in dt.Columns)
  621. {
  622. if (dc.Caption.ToLower() == caption)
  623. {
  624. return dc.ColumnName;
  625. }
  626. }
  627. return null;
  628. }
  629. //用于封装异常,也可以用于错误的提示
  630. public static void ShowError(string errorMessage)
  631. {
  632. throw new Exception(errorMessage);
  633. }
  634. /// <summary>
  635. /// 判断控件的某个事件是否已经绑定了方法
  636. /// </summary>
  637. /// <param name="Control1"></param>
  638. /// <param name="EventName"></param>
  639. /// <returns></returns>
  640. public static bool ControlHasEvent(Control Control1, string EventName)
  641. {
  642. //需要查询的内容
  643. BindingFlags myBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
  644. Assembly a = Assembly.GetAssembly(Control1.GetType());
  645. Type t = a.GetType(Control1.GetType().FullName, true);
  646. //获取控件的事件
  647. FieldInfo fi = t.GetField(EventName, myBindingFlags);
  648. EventHandlerList ehl = Control1.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).GetValue(Control1, null) as EventHandlerList;
  649. //判断事件的委托数量是否大于0
  650. if (ehl != null)
  651. {
  652. Delegate d = ehl[fi.GetValue(Control1)];
  653. if (d != null && d.GetInvocationList().Length > 0)
  654. {
  655. return true;
  656. }
  657. }
  658. return false;
  659. }
  660. /// <summary>
  661. /// 获取控件的事件列表
  662. /// </summary>
  663. /// <param name="Control1"></param>
  664. /// <returns></returns>
  665. public static FieldInfo[] GetControlsEvent(Control Control1)
  666. {
  667. BindingFlags myBindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
  668. Assembly a = Assembly.GetAssembly(Control1.GetType());
  669. Type t = a.GetType(Control1.GetType().FullName, true);
  670. FieldInfo[] finf = t.GetFields(myBindingFlags);
  671. return finf;
  672. }
  673. /// <summary>
  674. /// 清除DataTable的结构和数据,清除列结构时需要从最后的一列开始删
  675. /// </summary>
  676. /// <param name="dt"></param>
  677. public static void CleanDataTable(DataTable dt)
  678. {
  679. for (int i = dt.Columns.Count - 1; i >= 0; i--)
  680. dt.Columns.Remove(dt.Columns[i]);
  681. }
  682. /// <summary>
  683. /// 获取标签的路径
  684. /// </summary>
  685. /// <param name="URL"></param>
  686. /// <param name="LabelName"></param>
  687. /// <returns></returns>
  688. public static string GetLabelUrl(string URL, string LabelName)
  689. {
  690. ftpOperater ftp = new ftpOperater();
  691. return ftp.DownLoadFromSharePath(URL, LabelName);
  692. }
  693. /// <summary>
  694. /// 往DataTable中添加数据
  695. /// </summary>
  696. public static void AddDataToDataTable(DataTable dt, params string[] param)
  697. {
  698. DataRow dr = dt.NewRow();
  699. for (int i = 0; i < dt.Columns.Count; i++)
  700. {
  701. dr[dt.Columns[i].ColumnName] = param[i];
  702. }
  703. }
  704. /// <summary>
  705. /// 不清除表结构,只清除数据
  706. /// </summary>
  707. /// <param name="dt"></param>
  708. public static void CleanDataTableData(DataTable dt)
  709. {
  710. for (int i = dt.Rows.Count - 1; i >= 0; i--)
  711. {
  712. dt.Rows.Remove(dt.Rows[i]);
  713. }
  714. }
  715. /// <summary>
  716. /// 获取拼接的字段
  717. /// </summary>
  718. /// <param name="dt"></param>
  719. /// <returns></returns>
  720. public static string GetFieldFromDataTable(DataTable dt)
  721. {
  722. StringBuilder sb = new StringBuilder();
  723. foreach (DataColumn dc in dt.Columns)
  724. {
  725. sb.Append(dc.Caption + ",");
  726. }
  727. return sb.ToString().Substring(sb.ToString().Length - 1, 1);
  728. }
  729. /// <summary>
  730. /// 已经定义好的DataGridView绑定数据,operate是用来添加操作列的
  731. /// </summary>
  732. /// <param name="dgv"></param>
  733. /// <param name="dt"></param>
  734. /// <param name="AddOpetateColumn"></param>
  735. /// <param name="operate"></param>
  736. public static void FillDgvWithDataTable(DataGridView dgv, DataTable dt, params DataGridViewImageColumn[] operate)
  737. {
  738. dgv.AutoGenerateColumns = false;
  739. dgv.DataSource = dt;
  740. if (operate.Length > 0)
  741. {
  742. if (dgv.Columns[operate[0].Name] != null)
  743. {
  744. dgv.Columns.Remove(dgv.Columns[operate[0].Name]);
  745. }
  746. dgv.Columns.Add(operate[0]);
  747. }
  748. ////纯英文的列不予展示
  749. //Regex regEnglish = new Regex("^[A-z]+$");
  750. //foreach (DataGridViewColumn dgvc in dgv.Columns)
  751. //{
  752. // if (regEnglish.IsMatch(dgvc.HeaderText))
  753. // {
  754. // dgvc.Visible = false;
  755. // }
  756. //}
  757. }
  758. /// <summary>
  759. /// 清除DataGridView的数据
  760. /// </summary>
  761. /// <param name="dgv"></param>
  762. public static void CleanDGVData(DataGridView dgv)
  763. {
  764. for (int i = dgv.Rows.Count - 1; i >= 0; i--)
  765. {
  766. dgv.Rows.RemoveAt(i);
  767. }
  768. DataTable dt = dgv.DataSource as DataTable;
  769. if (dt != null)
  770. {
  771. dt.AcceptChanges();
  772. }
  773. }
  774. public static void CleanForm(Form Form)
  775. {
  776. for (int i = 0; i < Form.Controls.Count; i++)
  777. {
  778. if (Form.Controls[i].Controls.Count > 0)
  779. {
  780. CleanControls(Form.Controls[i].Controls);
  781. }
  782. if (Form.Controls[i] is EnterTextBox || Form.Controls[i] is TextBox || Form.Controls[i] is ValueLabel || Form.Controls[i] is SearchTextBox || Form.Controls[i] is ValueNumLabel || Form.Controls[i] is MaCodeSearchTextBox)
  783. Form.Controls[i].Text = "";
  784. if (Form.Controls[i] is DataGridView)
  785. CleanDGVData((DataGridView)Form.Controls[i]);
  786. }
  787. }
  788. public static void CleanControls(ControlCollection collection)
  789. {
  790. for (int i = 0; i < collection.Count; i++)
  791. {
  792. if (collection[i].Controls.Count > 0)
  793. CleanControls(collection[i].Controls);
  794. if (collection[i] is EnterTextBox || collection[i] is TextBox || collection[i] is ValueLabel || collection[i] is SearchTextBox || collection[i] is ValueNumLabel || collection[i] is MaCodeSearchTextBox)
  795. collection[i].Text = "";
  796. if (collection[i] is DataGridView)
  797. CleanDGVData((DataGridView)collection[i]);
  798. }
  799. }
  800. public static void CleanControlsText(params Control[] ctl)
  801. {
  802. foreach (Control item in ctl)
  803. item.Text = "";
  804. }
  805. /// <summary>
  806. /// 需要SQL的顺序和DGV的列的顺序一致
  807. /// </summary>
  808. /// <param name="dgv"></param>
  809. /// <param name="dt"></param>
  810. /// <param name="CheckBox"></param>
  811. public static void FillExpandDgvWithDataTable(DataGridViewExpand dgv, DataTable dt, bool CheckBox, bool CheckBoxTrue)
  812. {
  813. CleanDGVData(dgv);
  814. if (CheckBox)
  815. {
  816. for (int i = 0; i < dt.Rows.Count; i++)
  817. {
  818. CollapseDataGridViewRow collapseRow = new CollapseDataGridViewRow();
  819. collapseRow.IsCollapse = true;
  820. DataGridViewCheckBoxCell checkcell = new DataGridViewCheckBoxCell();
  821. collapseRow.Cells.Add(checkcell);
  822. checkcell.Value = CheckBoxTrue;
  823. //因为DGV中可能有空置的列多出,所以需要用DataTable的列进行循环
  824. for (int j = 0; j < dt.Columns.Count; j++)
  825. {
  826. DataGridViewTextBoxCell textcell = new DataGridViewTextBoxCell();
  827. textcell.Value = dt.Rows[i][j].ToString();
  828. collapseRow.Cells.Add(textcell);
  829. textcell.ReadOnly = true;
  830. }
  831. collapseRow.Tag = "MainRow";
  832. dgv.Rows.Add(collapseRow);
  833. }
  834. }
  835. else
  836. {
  837. for (int i = 0; i < dt.Rows.Count; i++)
  838. {
  839. CollapseDataGridViewRow collapseRow = new CollapseDataGridViewRow();
  840. collapseRow.IsCollapse = true;
  841. for (int j = 1; j <= dt.Columns.Count; j++)
  842. {
  843. DataGridViewTextBoxCell textcell = new DataGridViewTextBoxCell();
  844. textcell.Value = dt.Rows[i][j - 1].ToString();
  845. collapseRow.Cells.Add(textcell);
  846. }
  847. dgv.Rows.Add(collapseRow);
  848. collapseRow.ReadOnly = true;
  849. }
  850. }
  851. }
  852. /// <summary>
  853. /// 用于给DGV中的Combox列赋静态值
  854. /// </summary>
  855. /// <param name="dgvc"></param>
  856. /// <param name="displayField"></param>
  857. /// <param name="valueField"></param>
  858. /// <param name="Value"></param>
  859. /// <returns></returns>
  860. public static void SetDgvColumnComboxData(DataGridViewComboBoxColumn dgvc, string DataPropertyName, string displayField, string valueField, string[] Value)
  861. {
  862. DataTable dt = new DataTable();
  863. dt.Columns.Add(displayField);
  864. dt.Columns.Add(valueField);
  865. for (int i = 0; i < Value.Length; i++)
  866. {
  867. DataGridViewRow row = new DataGridViewRow();
  868. dt.Rows.Add(row);
  869. dt.Rows[i][displayField] = Value[i].Split('#')[0];
  870. dt.Rows[i][valueField] = Value[i].Split('#')[1];
  871. }
  872. dgvc.DataPropertyName = DataPropertyName;
  873. dgvc.DataSource = dt;
  874. dgvc.DisplayMember = displayField;
  875. dgvc.ValueMember = valueField;
  876. }
  877. /// <summary>
  878. /// 用于给DGV中的ComboxCell赋静态值
  879. /// </summary>
  880. /// <param name="dgvcc"></param>
  881. /// <param name="displayField"></param>
  882. /// <param name="valueField"></param>
  883. /// <param name="Value"></param>
  884. public static void SetDGVCellComboxData(DataGridViewComboBoxCell dgvcc, string displayField, string valueField, string[] Value)
  885. {
  886. DataTable dt = new DataTable();
  887. dt.Columns.Add(displayField);
  888. dt.Columns.Add(valueField);
  889. for (int i = 0; i < Value.Length; i++)
  890. {
  891. DataRow dr = dt.NewRow();
  892. dr[displayField] = Value[i].Split('#')[0];
  893. dr[valueField] = Value[i].Split('#')[1];
  894. dt.Rows.Add(dr);
  895. }
  896. dgvcc.DisplayMember = displayField;
  897. dgvcc.ValueMember = valueField;
  898. dgvcc.DataSource = dt;
  899. }
  900. /// <summary>
  901. /// 获取刷选的SQL语句,传入的是TextBox的Control,传入的SQL不带Where条件
  902. /// </summary>
  903. /// <param name="SQL"></param>
  904. /// <param name="Condition"></param>
  905. /// <returns></returns>
  906. public static string GetScreenSqlCondition(params Control[] Condition)
  907. {
  908. string condition = "";
  909. //用于统计传入的控件的空值数
  910. int EmptyControlCount = 0;
  911. for (int i = 0; i < Condition.Length; i++)
  912. {
  913. //如果Text不为空再进行条件的拼接
  914. if (Condition[i].Text != "")
  915. {
  916. if (Condition[i] is ComboBox)
  917. {
  918. condition += "(" + Condition[i].Tag + " like " + "'%" + (Condition[i] as ComboBox).SelectedValue + "%' )";
  919. }
  920. else
  921. {
  922. condition += "(" + Condition[i].Tag + " like " + "'%" + Condition[i].Text + "%' )";
  923. }
  924. //如果不是最后要判断之后有没有空值的如果有一个Text的值不为空都需要添加and
  925. //添加了一次And之后跳出循环,因为如果后面多项有值会重复添加and
  926. for (int j = i + 1; j < Condition.Length; j++)
  927. {
  928. if (j < Condition.Length)
  929. {
  930. if (Condition[j].Text != "")
  931. {
  932. condition += " and ";
  933. break;
  934. }
  935. }
  936. }
  937. }
  938. else
  939. {
  940. EmptyControlCount = EmptyControlCount + 1;
  941. }
  942. }
  943. //如果所有的控件传入的都是空值则返回也为空
  944. if (EmptyControlCount == Condition.Length)
  945. return "";
  946. else
  947. condition = " where " + condition;
  948. return condition;
  949. }
  950. public static void CleanDataGridView(DataGridView dgv)
  951. {
  952. for (int i = dgv.Columns.Count - 1; i >= 0; i--)
  953. {
  954. dgv.Columns.RemoveAt(i);
  955. }
  956. }
  957. /// <summary>
  958. /// 取出SQL中的参数占位符
  959. /// </summary>
  960. /// <param name="SQL"></param>
  961. /// <returns></returns>
  962. public static string[] GetParamFromSQL(string SQL)
  963. {
  964. string[] par = SQL.Split(':');
  965. //用来存参数的数组
  966. StringBuilder[] addpar = new StringBuilder[par.Length - 1];
  967. string[] param = new string[par.Length - 1];
  968. for (int i = 0; i < par.Length - 1; i++)
  969. {
  970. //新建一个char类型的数组用来存储每个字节的变量
  971. char[] c = par[i + 1].ToCharArray();
  972. addpar[i] = new StringBuilder();
  973. for (int j = 0; j < c.Length; j++)
  974. {
  975. if (c[j] != ' ' && c[j] != ',' && c[j] != ')')
  976. {
  977. addpar[i].Append(c[j]);
  978. }
  979. else
  980. {
  981. break;
  982. }
  983. }
  984. }
  985. for (int i = 0; i < par.Length - 1; i++)
  986. {
  987. param[i] = addpar[i].ToString();
  988. }
  989. return param;
  990. }
  991. public static void SetFormCenter(Form form)
  992. {
  993. form.StartPosition = FormStartPosition.CenterParent;
  994. }
  995. /// <summary>
  996. /// 设置DataGridView的指定列可编辑
  997. /// </summary>
  998. /// <param name="DGV"></param>
  999. /// <param name="EditAbleField"></param>
  1000. public static void SetDataGridViewReadOnly(DataGridView DGV, string[] EditAbleField)
  1001. {
  1002. foreach (DataGridViewColumn dc in DGV.Columns)
  1003. {
  1004. dc.ReadOnly = true;
  1005. foreach (string s in EditAbleField)
  1006. {
  1007. if (dc.Name.ToLower() == s.ToLower())
  1008. {
  1009. DGV.Columns[dc.Name].ReadOnly = false;
  1010. }
  1011. }
  1012. }
  1013. }
  1014. //判断带有CheckBox的DGV是否有项目勾选了
  1015. public static DataTable DGVIfChecked(DataGridView dgv)
  1016. {
  1017. int CheckCount = 0;
  1018. DataTable dt = new DataTable();
  1019. //第一列是勾选框,排除在循环之外
  1020. for (int i = 1; i < dgv.Columns.Count; i++)
  1021. {
  1022. dt.Columns.Add(dgv.Columns[i].Name);
  1023. }
  1024. for (int i = 0; i < dgv.RowCount; i++)
  1025. {
  1026. if (dgv.Rows[i].Cells[0].Value != null)
  1027. {
  1028. if (dgv.Rows[i].Cells[0].FormattedValue.ToString() == "True")
  1029. {
  1030. if (dgv.Rows[i].Tag.ToString() == "SonRow")
  1031. {
  1032. DataRow dr = dt.NewRow();
  1033. for (int j = 1; j < dgv.ColumnCount; j++)
  1034. {
  1035. dr[dgv.Columns[j].Name] = dgv.Rows[i].Cells[j].FormattedValue;
  1036. }
  1037. dt.Rows.Add(dr);
  1038. CheckCount++;
  1039. }
  1040. }
  1041. }
  1042. }
  1043. //判断是否勾选了明细
  1044. if (CheckCount == 0)
  1045. return null;
  1046. return dt;
  1047. }
  1048. public static void GetExpandDGVCheckedRow(DataGridView dgv, DataTable dt, int RowIndex, int DistinctColumnIndex)
  1049. {
  1050. //第一列是勾选框,排除在循环之外
  1051. if (dt.Columns.Count == 0)
  1052. {
  1053. for (int i = 0; i < dgv.Columns.Count; i++)
  1054. dt.Columns.Add(dgv.Columns[i].Name);
  1055. }
  1056. //是展开的子行的数据
  1057. if (dgv.Rows[RowIndex].Tag != null && dgv.Rows[RowIndex].Tag.ToString() == "SonRow")
  1058. {
  1059. DataRow dr = dt.NewRow();
  1060. DataRow[] datarow = (dt.Select(dgv.Columns[DistinctColumnIndex].Name + " ='" + dgv.Rows[RowIndex].Cells[DistinctColumnIndex].FormattedValue + "'"));
  1061. //判断值是否存在,存在移除重新添加
  1062. if (datarow.Length > 0)
  1063. {
  1064. dt.Rows.Remove(datarow[0]);
  1065. }
  1066. for (int j = 0; j < dgv.ColumnCount; j++)
  1067. {
  1068. dr[dgv.Columns[j].Name] = dgv.Rows[RowIndex].Cells[j].FormattedValue;
  1069. }
  1070. dt.Rows.Add(dr);
  1071. }
  1072. }
  1073. /// <summary>
  1074. /// 设置只允许输入数字
  1075. /// </summary>
  1076. /// <param name="sender"></param>
  1077. /// <param name="e"></param>
  1078. public static void NumOnly(object sender, KeyPressEventArgs e)
  1079. {
  1080. if (e.KeyChar != '\b')//这是允许输入退格键
  1081. {
  1082. if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字
  1083. {
  1084. e.Handled = true;
  1085. }
  1086. }
  1087. }
  1088. public static string AddField(string[] Fields)
  1089. {
  1090. string sql = " ";
  1091. foreach (string field in Fields)
  1092. sql += field + ",";
  1093. return sql.Substring(0, sql.Length - 1);
  1094. }
  1095. /// <summary>
  1096. /// 筛选DataTable
  1097. /// </summary>
  1098. /// <param name="dt"></param>
  1099. /// <param name="condition"></param>
  1100. /// <returns></returns>
  1101. public static DataTable filterDataTable(DataTable dt, String condition)
  1102. {
  1103. if (dt == null)
  1104. return new DataTable();
  1105. //获取筛选条件中的列名,值
  1106. DataRow[] dataRows = dt.Select(condition);
  1107. DataTable ndt = dt.Clone();
  1108. for (int i = 0; i < dataRows.Length; i++)
  1109. {
  1110. ndt.Rows.Add(dataRows[i].ItemArray);
  1111. }
  1112. return ndt;
  1113. }
  1114. /// <summary>
  1115. /// 图表绘制公共方法样本
  1116. /// </summary>
  1117. /// <param name="chart1"></param>
  1118. /// <param name="_dt"></param>
  1119. /// <param name="seriesChartType"></param>
  1120. /// <param name="_title"></param>
  1121. /// <param name="XValueMember"></param>
  1122. /// <param name="YValueMembers"></param>
  1123. /// <param name="Xname"></param>
  1124. /// <param name="Yname"></param>
  1125. public static void ViewChart(Chart chart1, DataTable _dt, SeriesChartType seriesChartType, string _title, string XValueMember, string YValueMembers, string Xname, string Yname)
  1126. {
  1127. chart1.Series[0].ChartType = seriesChartType;
  1128. chart1.DataSource = _dt;
  1129. chart1.Series[0].MarkerStyle = MarkerStyle.Circle;
  1130. chart1.Series[0].MarkerSize = 8;
  1131. chart1.Series[0].XValueMember = XValueMember;
  1132. chart1.Series[0].YValueMembers = YValueMembers;
  1133. chart1.Series[0].Label = "#VAL";
  1134. chart1.Series[0].LabelToolTip = Xname + ": #VAL\r\n " + Yname + " #VALX";
  1135. chart1.Series[0].BackSecondaryColor = Color.DarkCyan;
  1136. chart1.Series[0].BorderColor = Color.DarkOliveGreen;
  1137. chart1.Series[0].LabelBackColor = Color.Transparent;
  1138. chart1.Series[0].LegendText = Yname;
  1139. chart1.Legends[0].Title = _title;
  1140. //chart1.ChartAreas[0].Area3DStyle.Enable3D = true;
  1141. }
  1142. /// <summary>
  1143. /// 将新增打印进程信息写入静态文件
  1144. /// </summary>
  1145. /// <param name="lbl"></param>
  1146. public static void WriteLbl(ApplicationClass lbl)
  1147. {
  1148. Process[] processes = System.Diagnostics.Process.GetProcessesByName("lppa");
  1149. Dictionary<string, int> ProInf = new Dictionary<string, int>();
  1150. for (int i = 0; i < processes.Length; i++)
  1151. {
  1152. try
  1153. {
  1154. if (processes[i].ProcessName == "lppa")
  1155. {
  1156. ProInf.Add(processes[i].StartTime.ToString(), processes[i].Id);
  1157. }
  1158. }
  1159. catch
  1160. {
  1161. }
  1162. }
  1163. var temp = ProInf.Keys.Max();
  1164. String str = SystemInf.ProcessesID + "|" + ProInf[temp];
  1165. FileStream fs = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Append, FileAccess.Write);
  1166. StreamWriter sw = new StreamWriter(fs);
  1167. sw.WriteLine(str, Encoding.UTF8);
  1168. sw.Close();
  1169. fs.Close();
  1170. }
  1171. public static void WriteLbl()
  1172. {
  1173. //Process[] processes = System.Diagnostics.Process.GetProcessesByName("lppa");
  1174. //Dictionary<string, int> ProInf = new Dictionary<string, int>();
  1175. //for (int i = 0; i < processes.Length; i++)
  1176. //{
  1177. // try
  1178. // {
  1179. // if (processes[i].ProcessName == "lppa")
  1180. // {
  1181. // ProInf.Add(processes[i].StartTime.ToString(), processes[i].Id);
  1182. // }
  1183. // }
  1184. // catch
  1185. // {
  1186. // }
  1187. //}
  1188. //var temp = ProInf.Keys.Max();
  1189. //String str = SystemInf.ProcessesID + "|" + ProInf[temp];
  1190. //FileStream fs = new FileStream(SystemInf.CacheFolder + "lblprocess.txt", FileMode.Append, FileAccess.Write);
  1191. //StreamWriter sw = new StreamWriter(fs);
  1192. //sw.WriteLine(str, Encoding.UTF8);
  1193. //sw.Close();
  1194. //fs.Close();
  1195. }
  1196. public static Object GetCacheData(string ParamName)
  1197. {
  1198. try
  1199. {
  1200. Object o = null;
  1201. //根据地址读取xml文件
  1202. XmlDocument doc = new XmlDocument();
  1203. XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
  1204. //忽略文档里面的注释
  1205. settings.IgnoreComments = true;
  1206. XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
  1207. doc.Load(reader);
  1208. //先得到根节点
  1209. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  1210. //再由根节点去找制定的节点
  1211. XmlNodeList nodeList = rootNode.ChildNodes;
  1212. foreach (XmlNode node in nodeList)
  1213. {
  1214. //找到了这个节点名字
  1215. if (node.Name == ParamName)
  1216. {
  1217. //返回节点的内容
  1218. switch (((XmlElement)node).GetAttribute("Type"))
  1219. {
  1220. case "System.String":
  1221. o = node.InnerText;
  1222. break;
  1223. case "System.Int32":
  1224. o = int.Parse(node.InnerText);
  1225. break;
  1226. case "System.Boolean":
  1227. o = node.InnerText == "True" ? true : false;
  1228. break;
  1229. default:
  1230. break;
  1231. }
  1232. break;
  1233. }
  1234. }
  1235. //关闭reader
  1236. reader.Close();
  1237. if (o == null)
  1238. return "";
  1239. else
  1240. return o;
  1241. }
  1242. catch (Exception e)
  1243. {
  1244. LogManager.DoLog(e.Message);
  1245. return "";
  1246. }
  1247. }
  1248. public static void SetCacheData(string ParamName, object Value)
  1249. {
  1250. try
  1251. {
  1252. //根据地址读取xml文件
  1253. XmlDocument doc = new XmlDocument();
  1254. XmlReaderSettings settings = new XmlReaderSettings { CheckCharacters = false };
  1255. //忽略文档里面的注释
  1256. settings.IgnoreComments = true;
  1257. XmlReader reader = XmlReader.Create(SystemInf.CacheFilePath, settings);
  1258. doc.Load(reader);
  1259. //先得到根节点
  1260. XmlNode rootNode = doc.SelectSingleNode("cacheInfo");
  1261. //再由根节点去找制定的节点
  1262. XmlNodeList nodeList = rootNode.ChildNodes;
  1263. bool flag = false;
  1264. foreach (XmlNode node in nodeList)
  1265. {
  1266. //找到了这个节点名字
  1267. if (node.Name == ParamName)
  1268. {
  1269. //就直接赋值
  1270. node.InnerText = Value.ToString();
  1271. flag = true;
  1272. }
  1273. }
  1274. //如果没有该节点,就创建节点保存结果
  1275. if (!flag)
  1276. {
  1277. //创建节点
  1278. XmlElement newNode = doc.CreateElement(ParamName);
  1279. XmlAttribute attr = doc.CreateAttribute("Type");
  1280. attr.InnerText = Value.GetType().ToString();
  1281. newNode.InnerText = Value.ToString();
  1282. newNode.SetAttributeNode(attr);
  1283. //讲新建的节点挂到根节点上
  1284. rootNode.AppendChild(newNode);
  1285. }
  1286. //关闭Reader
  1287. reader.Close();
  1288. doc.Save(SystemInf.CacheFilePath);
  1289. }
  1290. catch (Exception e)
  1291. {
  1292. LogManager.DoLog(e.Message);
  1293. }
  1294. }
  1295. public static void ClosePrint(ApplicationClass lbl)
  1296. {
  1297. lblpro = lbl;
  1298. Thread close = new Thread(ClosePrintProcess);
  1299. close.Start();
  1300. }
  1301. public static void ClosePrint(Engine lbl)
  1302. {
  1303. eng = lbl;
  1304. Thread close = new Thread(ClosePrintProcess);
  1305. close.Start();
  1306. }
  1307. static Engine eng;
  1308. static ApplicationClass lblpro;
  1309. private static void ClosePrintProcess()
  1310. {
  1311. try
  1312. {
  1313. eng.Stop();
  1314. }
  1315. catch (Exception)
  1316. {
  1317. }
  1318. }
  1319. public static bool connectState(string path)
  1320. {
  1321. return connectState(path, "vsftpd", "vsftpd");
  1322. }
  1323. /// <summary>
  1324. /// 连接远程共享文件夹
  1325. /// </summary>
  1326. /// <param name="path">远程共享文件夹的路径</param>
  1327. /// <param name="userName">用户名</param>
  1328. /// <param name="passWord">密码</param>
  1329. /// <returns></returns>
  1330. public static bool connectState(string path, string userName, string passWord)
  1331. {
  1332. bool Flag = false;
  1333. Process proc = new Process();
  1334. try
  1335. {
  1336. proc.StartInfo.FileName = "cmd.exe";
  1337. proc.StartInfo.UseShellExecute = false;
  1338. proc.StartInfo.RedirectStandardInput = true;
  1339. proc.StartInfo.RedirectStandardOutput = true;
  1340. proc.StartInfo.RedirectStandardError = true;
  1341. proc.StartInfo.CreateNoWindow = true;
  1342. proc.Start();
  1343. string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
  1344. proc.StandardInput.WriteLine(dosLine);
  1345. proc.StandardInput.WriteLine("exit");
  1346. while (!proc.HasExited)
  1347. {
  1348. proc.WaitForExit(1);
  1349. }
  1350. string errormsg = proc.StandardError.ReadToEnd();
  1351. proc.StandardError.Close();
  1352. if (string.IsNullOrEmpty(errormsg))
  1353. {
  1354. Flag = true;
  1355. }
  1356. else
  1357. {
  1358. throw new Exception(errormsg);
  1359. }
  1360. }
  1361. catch (Exception ex)
  1362. {
  1363. LogManager.DoLog(ex.Message);
  1364. }
  1365. finally
  1366. {
  1367. proc.Close();
  1368. proc.Dispose();
  1369. }
  1370. return Flag;
  1371. }
  1372. /// <summary>
  1373. /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
  1374. /// </summary>
  1375. /// <param name="src">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
  1376. /// <param name="dst">保存文件的路径,不含名称及扩展名</param>
  1377. /// <param name="fileName">保存文件的名称以及扩展名</param>
  1378. public static void Transport(string src, string dst, string fileName)
  1379. {
  1380. FileStream inFileStream = new FileStream(src, FileMode.Open);
  1381. if (!Directory.Exists(dst))
  1382. {
  1383. Directory.CreateDirectory(dst);
  1384. }
  1385. dst = dst + fileName;
  1386. FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
  1387. byte[] buf = new byte[inFileStream.Length];
  1388. int byteCount;
  1389. while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
  1390. {
  1391. outFileStream.Write(buf, 0, byteCount);
  1392. }
  1393. inFileStream.Flush();
  1394. inFileStream.Close();
  1395. outFileStream.Flush();
  1396. outFileStream.Close();
  1397. }
  1398. /// <summary>
  1399. /// 取两个DataTable的交集,删除重复数据
  1400. /// </summary>
  1401. /// <param name="sourceDataTable"></param>
  1402. /// <param name="targetDataTable"></param>
  1403. /// <param name="primaryKey"></param>
  1404. /// <returns></returns>
  1405. public static DataTable DataTableMerge(DataTable sourceDataTable, DataTable targetDataTable, string primaryKey)
  1406. {
  1407. if (sourceDataTable != null || targetDataTable != null || !sourceDataTable.Equals(targetDataTable))
  1408. {
  1409. sourceDataTable.PrimaryKey = new DataColumn[] { sourceDataTable.Columns[primaryKey] };
  1410. DataTable dt = targetDataTable.Copy();
  1411. foreach (DataRow tRow in dt.Rows)
  1412. {
  1413. try
  1414. {
  1415. //拒绝自上次调用 System.Data.DataRow.AcceptChanges() 以来对该行进行的所有更改。
  1416. //因为行状态为DataRowState.Deleted时无法访问ItemArray的值
  1417. tRow.RejectChanges();
  1418. //在加载数据时关闭通知、索引维护和约束。
  1419. sourceDataTable.BeginLoadData();
  1420. //查找和更新特定行。如果找不到任何匹配行,则使用给定值创建新行。
  1421. DataRow temp = sourceDataTable.LoadDataRow(tRow.ItemArray, false);
  1422. sourceDataTable.EndLoadData();
  1423. sourceDataTable.Rows.Remove(temp);
  1424. }
  1425. catch
  1426. {
  1427. }
  1428. }
  1429. }
  1430. sourceDataTable.AcceptChanges();
  1431. return sourceDataTable;
  1432. }
  1433. //将DataRow[] 转换成DataTable
  1434. public static DataTable ToDataTable(DataRow[] rows)
  1435. {
  1436. if (rows == null || rows.Length == 0) return new DataTable();
  1437. DataTable tmp = rows[0].Table.Clone(); // 复制DataRow的表结构
  1438. foreach (DataRow row in rows)
  1439. tmp.Rows.Add(row.ItemArray); // 将DataRow添加到DataTable中
  1440. return tmp;
  1441. }
  1442. /// <summary>
  1443. ///
  1444. /// </summary>
  1445. /// <param name="form"></param>
  1446. /// <param name="InOrOut">True表示打开窗体,False表示关闭窗体</param>
  1447. public static void FormStepInOrOut(Form form, bool InOrOut)
  1448. {
  1449. if (InOrOut)
  1450. {
  1451. for (int iNum = 0; iNum <= 10; iNum++)
  1452. {
  1453. //变更窗体的不透明度
  1454. form.Opacity = 0.1 * iNum;
  1455. //暂停
  1456. System.Threading.Thread.Sleep(20);
  1457. }
  1458. }
  1459. else
  1460. {
  1461. for (int iNum = 10; iNum >= 0; iNum--)
  1462. {
  1463. //变更窗体的不透明度
  1464. form.Opacity = 0.1 * iNum;
  1465. //暂停
  1466. System.Threading.Thread.Sleep(20);
  1467. }
  1468. }
  1469. }
  1470. public static string GetDataFromDevice(string Param)
  1471. {
  1472. String cmd = System.Windows.Forms.Application.StartupPath + "\\adb.exe";
  1473. Process p = new Process();
  1474. p.StartInfo = new System.Diagnostics.ProcessStartInfo();
  1475. p.StartInfo.FileName = cmd;//设定程序名
  1476. p.StartInfo.UseShellExecute = false; //关闭shell的使用
  1477. p.StartInfo.RedirectStandardInput = true; //重定向标准输入
  1478. p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
  1479. p.StartInfo.RedirectStandardError = true; //重定向错误输出
  1480. p.StartInfo.CreateNoWindow = true;//设置不显示窗口
  1481. string value = "";
  1482. switch (Param)
  1483. {
  1484. case "IMEI":
  1485. p.StartInfo.Arguments = " shell \n su \n service call iphonesubinfo 1";
  1486. p.Start();
  1487. try
  1488. {
  1489. p.StandardInput.Close();
  1490. string IMEI = p.StandardOutput.ReadToEnd();
  1491. foreach (System.Text.RegularExpressions.Match item in Regex.Matches(IMEI, "'\\S+"))
  1492. {
  1493. value += item.Value.Replace(".", "").Replace("'", "").Replace(")", "");
  1494. }
  1495. p.Close();
  1496. }
  1497. catch (Exception ex)
  1498. {
  1499. Console.WriteLine(ex.Message);
  1500. }
  1501. break;
  1502. case "POWER":
  1503. p.StartInfo.Arguments = " shell dumpsys battery";
  1504. p.Start();
  1505. value = Regex.Match(p.StandardOutput.ReadToEnd().ToUpper(), "LEVEL: \\d+").Value.Replace("LEVEL: ", "");
  1506. p.Close();
  1507. break;
  1508. case "MAC":
  1509. p.StartInfo.Arguments = " shell cat /sys/class/net/wlan0/address";
  1510. p.Start();
  1511. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1512. p.Close();
  1513. break;
  1514. case "BT":
  1515. p.StartInfo.Arguments = " shell settings get secure bluetooth_address";
  1516. p.Start();
  1517. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1518. p.Close();
  1519. break;
  1520. case "SPEC":
  1521. p.StartInfo.Arguments = " -d shell getprop ro.product.model";
  1522. p.Start();
  1523. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1524. p.Close();
  1525. break;
  1526. case "VERSION":
  1527. p.StartInfo.Arguments = " shell getprop ro.build.display.id";
  1528. p.Start();
  1529. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1530. p.Close();
  1531. break;
  1532. case "CUS_VERSION":
  1533. p.StartInfo.Arguments = " shell getprop ro.elinktek.version.release";
  1534. p.Start();
  1535. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1536. p.Close();
  1537. break;
  1538. case "SN":
  1539. p.StartInfo.Arguments = " shell getprop ro.serialno";
  1540. p.Start();
  1541. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1542. p.Close();
  1543. break;
  1544. case "RESET":
  1545. p.StartInfo.Arguments = " reboot recovery";
  1546. p.Start();
  1547. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1548. p.Close();
  1549. break;
  1550. default:
  1551. break;
  1552. }
  1553. Console.WriteLine(Param + " : " + value.Trim());
  1554. return value.Trim();
  1555. }
  1556. public static string GetDataFromDevice(string Param, string Path)
  1557. {
  1558. String cmd = System.Windows.Forms.Application.StartupPath + "\\adb.exe";
  1559. Process p = new Process();
  1560. p.StartInfo = new System.Diagnostics.ProcessStartInfo();
  1561. p.StartInfo.FileName = cmd;//设定程序名
  1562. p.StartInfo.UseShellExecute = false; //关闭shell的使用
  1563. p.StartInfo.RedirectStandardInput = true; //重定向标准输入
  1564. p.StartInfo.RedirectStandardOutput = true; //重定向标准输出
  1565. p.StartInfo.RedirectStandardError = true; //重定向错误输出
  1566. p.StartInfo.CreateNoWindow = true;//设置不显示窗口
  1567. string value = "";
  1568. switch (Param)
  1569. {
  1570. case "GETFILE":
  1571. p.StartInfo.Arguments = " pull " + Path;
  1572. p.Start();
  1573. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1574. p.Close();
  1575. break;
  1576. case "INSTALL":
  1577. p.StartInfo.Arguments = " install " + Path;
  1578. p.Start();
  1579. value = p.StandardOutput.ReadToEnd().Replace(":", "").ToUpper();
  1580. p.Close();
  1581. break;
  1582. default:
  1583. break;
  1584. }
  1585. Console.WriteLine(Param + " : " + value.Trim());
  1586. return value.Trim();
  1587. }
  1588. public static void GetWriteInfo(string FilePath, out string BARCODE, out string MAC, out string BT, out string IMEI0, out string IMEI1)
  1589. {
  1590. MAC = "";
  1591. BT = "";
  1592. IMEI0 = "";
  1593. IMEI1 = "";
  1594. BARCODE = "";
  1595. string txt = "";
  1596. while (true)
  1597. {
  1598. try
  1599. {
  1600. StreamReader sr = new StreamReader(FilePath);
  1601. while (!sr.EndOfStream)
  1602. {
  1603. string str = sr.ReadLine().ToUpper();
  1604. txt += str + "\n";
  1605. }
  1606. IMEI0 = Regex.Match(txt, "IMEI[0] = \\S[0-9]{15}\\S").Value.Replace("IMEI[", "").Replace("]", "");
  1607. IMEI1 = Regex.Match(txt, "IMEI[1] = \\S[0-9]{15}\\S").Value.Replace("IMEI[", "").Replace("]", "");
  1608. MAC = Regex.Match(txt, "WIFIADDRESS = \\[\\S+\\]").Value.Replace("WIFIADDRESS = [", "").Replace("]", "").Replace(":", "");
  1609. BT = Regex.Match(txt, "BTADDRESS = \\[\\S+\\]").Value.Replace("BTADDRESS = [", "").Replace("]", "").Replace(":", "");
  1610. BARCODE = Regex.Match(txt, "BARCODE = \\[\\S+\\]").Value.Replace("BARCODE = [", "").Replace("]", "").Replace(":", "");
  1611. if (BARCODE == "")
  1612. {
  1613. IMEI0 = Regex.Match(txt, "IMEI1\\s+'\\d+'").Value.Replace("IMEI1", "").Replace("'", "").Trim();
  1614. MAC = Regex.Match(txt, "WIFI\\s+'\\S+'").Value.Replace("WIFI", "").Replace("'", "").Trim();
  1615. BT = Regex.Match(txt, "BT\\s+'\\S+'").Value.Replace("BT", "").Replace("'", "").Trim();
  1616. BARCODE = Regex.Match(txt, "SN1\\s+'\\S+'").Value.Replace("SN1", "").Replace("'", "").Trim();
  1617. }
  1618. break;
  1619. }
  1620. catch (Exception e)
  1621. {
  1622. Console.WriteLine(e.Message);
  1623. Thread.Sleep(1000);
  1624. }
  1625. }
  1626. }
  1627. public static bool OpenCSVFile(ref DataTable mycsvdt, string filepath)
  1628. {
  1629. string strpath = filepath; //csv文件的路径
  1630.             try
  1631. {
  1632. int intColCount = 0;
  1633. bool blnFlag = true;
  1634. DataColumn mydc;
  1635. DataRow mydr;
  1636. string strline;
  1637. string[] aryline;
  1638. StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.UTF8);
  1639. while ((strline = mysr.ReadLine()) != null)
  1640. {
  1641. aryline = strline.Split(new char[] { ',' });
  1642. //给datatable加上列名
  1643. if (blnFlag)
  1644. {
  1645. blnFlag = false;
  1646. intColCount = aryline.Length;
  1647. int col = 0;
  1648. for (int i = 0; i < aryline.Length; i++)
  1649. {
  1650. col = i + 1;
  1651. mydc = new DataColumn(col.ToString());
  1652. mycsvdt.Columns.Add(mydc);
  1653. }
  1654. }
  1655. //填充数据并加入到datatable中
  1656. mydr = mycsvdt.NewRow();
  1657. for (int i = 0; i < aryline.Length; i++)
  1658. {
  1659. mydr[i] = aryline[i];
  1660. }
  1661. if (mydr[0].ToString() != "")
  1662. mycsvdt.Rows.Add(mydr);
  1663. }
  1664. mysr.Close();
  1665. return true;
  1666. }
  1667. catch (Exception ex)
  1668. {
  1669. Console.WriteLine(ex.Message + ex.StackTrace);
  1670. return false;
  1671. }
  1672. }
  1673. }
  1674. }