CommonHelper.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. using PDF_Master.Model.PageEdit;
  2. using PDF_Master.ViewModels.Dialog.BOTA;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Runtime.InteropServices;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. using System.Threading.Tasks;
  13. using System.Windows;
  14. using System.Windows.Media;
  15. namespace PDF_Master.Helper
  16. {
  17. public class Compare<T, C> : IEqualityComparer<T>
  18. {
  19. private Func<T, C> _getField;
  20. public Compare(Func<T, C> getfield)
  21. {
  22. this._getField = getfield;
  23. }
  24. public bool Equals(T x, T y)
  25. {
  26. return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
  27. }
  28. public int GetHashCode(T obj)
  29. {
  30. return EqualityComparer<C>.Default.GetHashCode(this._getField(obj));
  31. }
  32. }
  33. public enum FileExtension
  34. {
  35. JPG = 255216,
  36. GIF = 7173,
  37. PNG = 13780,
  38. SWF = 6787,
  39. RAR = 8297,
  40. ZIP = 8075,
  41. _7Z = 55122,
  42. VALIDFILE = 9999999
  43. }
  44. /// <summary>
  45. /// 1 FindVisualParent 查找目标类型的父类控件
  46. /// 2 FindVisualChild 查找目标类型的子类控件
  47. /// 3 GetPageParmFromList 从页码集合获取页码字符串,如1,2,3 转换成1-3
  48. /// 4 GetPagesInRange 校验PageRange 输入是否合法,且可返回List<int> Pages 存放的索引值
  49. /// 5.ShowFileBrowser 显示系统文件浏览器,可以根据传入的路径参数,自动选中对应的文件
  50. /// 6.CreateFilePath 检查对应路径是否有重名,有重名的情况追加尾号
  51. /// 7.CreateFolder 检查对应文件夹是否有重名,有重名的情况追加尾号
  52. /// 8.GetUnitsFromPageSize 将PDF页面宽高转换成对应的单位
  53. /// 9.GetDpi() 返回当前设备DPI
  54. /// 10.GetFileSize() 获取文件大小
  55. /// </summary>
  56. public static class CommonHelper
  57. {
  58. [DllImport("user32.dll")]
  59. private static extern IntPtr SetCapture(long hWnd);
  60. [DllImport("user32.dll")]
  61. private static extern long ReleaseCapture();
  62. /// <summary>
  63. /// 打开路径并定位文件...对于@"h:\Bleacher Report - Hardaway with the safe call ??.mp4"这样的,explorer.exe /select,d:xxx不认,用API整它
  64. /// </summary>
  65. /// <param name="filePath">文件绝对路径</param>
  66. [DllImport("shell32.dll", ExactSpelling = true)]
  67. private static extern void ILFree(IntPtr pidlList);
  68. [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
  69. private static extern IntPtr ILCreateFromPathW(string pszPath);
  70. [DllImport("shell32.dll", ExactSpelling = true)]
  71. private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);
  72. /// <summary>
  73. /// 打开文件夹浏览,并选中一个文件(对于文件名称比较不规范的,可以用这个)
  74. /// </summary>
  75. /// <param name="filePath"></param>
  76. public static void ExplorerFile(string filePath)
  77. {
  78. try
  79. {
  80. if (!File.Exists(filePath) && !Directory.Exists(filePath))
  81. return;
  82. if (Directory.Exists(filePath))
  83. Process.Start(@"explorer.exe", "/select,\"" + filePath + "\"");
  84. else
  85. {
  86. IntPtr pidlList = ILCreateFromPathW(filePath);
  87. if (pidlList != IntPtr.Zero)
  88. {
  89. try
  90. {
  91. Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
  92. }
  93. finally
  94. {
  95. ILFree(pidlList);
  96. }
  97. }
  98. }
  99. }
  100. catch { }
  101. }
  102. /// <summary>
  103. /// 自定义Distinct扩展方法
  104. /// </summary>
  105. /// <typeparam name="T">要去重的对象类</typeparam>
  106. /// <typeparam name="C">自定义去重的字段类型</typeparam>
  107. /// <param name="source">要去重的对象</param>
  108. /// <param name="getfield">获取自定义去重字段的委托</param>
  109. /// <returns></returns>
  110. public static IEnumerable<T> DistinctHelper<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
  111. {
  112. return source.Distinct(new Compare<T, C>(getfield));
  113. }
  114. /// <summary>
  115. /// 查找对象目标类型的父类控件
  116. /// </summary>
  117. /// <typeparam name="T"></typeparam>
  118. /// <param name="obj"></param>
  119. /// <returns></returns>
  120. public static T FindVisualParent<T>(DependencyObject obj) where T : class
  121. {
  122. try
  123. {
  124. while (obj != null)
  125. {
  126. if (obj is T)
  127. return obj as T;
  128. obj = VisualTreeHelper.GetParent(obj);
  129. }
  130. return null;
  131. }
  132. catch { return null; }
  133. }
  134. /// <summary>
  135. /// 根据对象查找目标类型的子类
  136. /// </summary>
  137. /// <typeparam name="childItem"></typeparam>
  138. /// <param name="obj"></param>
  139. /// <returns></returns>
  140. public static childItem FindVisualChild<childItem>(DependencyObject obj)
  141. where childItem : DependencyObject
  142. {
  143. try
  144. {
  145. for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
  146. {
  147. DependencyObject child = VisualTreeHelper.GetChild(obj, i);
  148. if (child != null && child is childItem)
  149. return (childItem)child;
  150. else
  151. {
  152. childItem childOfChild = FindVisualChild<childItem>(child);
  153. if (childOfChild != null)
  154. return childOfChild;
  155. }
  156. }
  157. return null;
  158. }
  159. catch { return null; }
  160. }
  161. public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
  162. {
  163. for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
  164. {
  165. var child = VisualTreeHelper.GetChild(parent, i);
  166. string controlName = child.GetValue(System.Windows.Controls.Control.NameProperty) as string;
  167. if (controlName == name)
  168. {
  169. return child as T;
  170. }
  171. else
  172. {
  173. T result = FindVisualChildByName<T>(child, name);
  174. if (result != null)
  175. return result;
  176. }
  177. }
  178. return null;
  179. }
  180. /// <summary>
  181. /// 从页码集合获取页码字符串,如1,2,3 转换成1-3
  182. /// </summary>
  183. /// <param name="pagesList"></param>
  184. /// <returns></returns>
  185. public static string GetPageParmFromList(List<int> pagesList)
  186. {
  187. string pageParam = "";
  188. if (pagesList.Count != 0)
  189. {
  190. pagesList.Sort();//先对页码排序
  191. for (int i = 0; i < pagesList.Count; i++)
  192. {
  193. if (i == 0)
  194. {
  195. pageParam += pagesList[0].ToString();
  196. }
  197. else
  198. {
  199. if (pagesList[i] == pagesList[i - 1] + 1)//页码连续
  200. {
  201. if (i >= 2)
  202. {
  203. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  204. pageParam += "-";
  205. }
  206. else
  207. pageParam += "-";
  208. if (i == pagesList.Count - 1)
  209. {
  210. pageParam += pagesList[i].ToString();
  211. }
  212. }
  213. else//页码不连续时
  214. {
  215. if (i >= 2)
  216. {
  217. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  218. pageParam += pagesList[i - 1].ToString();
  219. }
  220. pageParam += "," + pagesList[i].ToString();
  221. }
  222. }
  223. }
  224. }
  225. return pageParam;
  226. }
  227. /// <summary>
  228. /// 校验PageRange 输入是否合法,且可返回List<int> Pages 存放的索引值
  229. /// </summary>
  230. /// <param name="pageIndexList">返回的页面索引集合</param>
  231. /// <param name="pageRange">需要判断的文本</param>
  232. /// <param name="count">页面总数</param>
  233. /// <param name="enumerationSeparator">例 new char[] { ',' }</param>
  234. /// <param name="rangeSeparator">例 new char[] { '-' }</param>
  235. /// <param name="inittag"></param>
  236. /// <returns></returns>
  237. public static bool GetPagesInRange(ref List<int> pageIndexList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false)
  238. {
  239. string[] rangeSplit = pageRange.Split(enumerationSeparator);//根据分隔符 拆分字符串
  240. pageIndexList.Clear();
  241. foreach (string range in rangeSplit)
  242. {
  243. int starttag = 1;
  244. if (inittag)
  245. {
  246. starttag = 0;
  247. }
  248. if (range.Contains("-"))//连续页
  249. {
  250. try
  251. {
  252. string[] limits = range.Split(rangeSeparator);//对子字符串再根据”-“ 拆分
  253. if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1]))
  254. {
  255. int start = int.Parse(limits[0]);
  256. int end = int.Parse(limits[1]);
  257. if ((start < starttag) || (end > count) || (start > end))
  258. {
  259. return false;
  260. }
  261. for (int i = start; i <= end; ++i)
  262. {
  263. if (pageIndexList.Contains(i))
  264. {
  265. return false;
  266. }
  267. pageIndexList.Add(i - 1);
  268. }
  269. continue;
  270. }
  271. }
  272. catch
  273. {
  274. return false;
  275. }
  276. }
  277. int pageNr;
  278. try
  279. {
  280. // Single page
  281. pageNr = int.Parse(range);//单页
  282. }
  283. catch//格式不正确时
  284. {
  285. return false;
  286. }
  287. if (pageNr < starttag || pageNr > count)
  288. {
  289. return false;
  290. }
  291. if (pageIndexList.Contains(pageNr))
  292. {
  293. return false;
  294. }
  295. pageIndexList.Add(pageNr - 1);
  296. }
  297. return true;
  298. }
  299. /// <summary>
  300. /// 显示系统文件浏览器
  301. /// </summary>
  302. /// <param name="selectedFile">要选中的文件路径</param>
  303. public static void ShowFileBrowser(string selectedFile = null)
  304. {
  305. if (string.IsNullOrEmpty(selectedFile))
  306. {
  307. Process.Start(@"explorer.exe");
  308. }
  309. else
  310. {
  311. Process.Start(@"explorer.exe", "/select,\"" + selectedFile + "\"");
  312. }
  313. }
  314. /// <summary>
  315. /// 检测文件是否重复 追加尾号
  316. /// </summary>
  317. /// <param name="path"></param>
  318. /// <returns></returns>
  319. public static string CreateFilePath(string path)
  320. {
  321. int i = 1;
  322. string oldDestName = path;
  323. do
  324. {
  325. if (File.Exists(path))
  326. {
  327. int lastDot = oldDestName.LastIndexOf('.');
  328. string fileExtension = string.Empty;
  329. string fileName = oldDestName;
  330. if (lastDot > 0)
  331. {
  332. fileExtension = fileName.Substring(lastDot);
  333. fileName = fileName.Substring(0, lastDot);
  334. }
  335. path = fileName + string.Format(@"({0})", i) + fileExtension;
  336. }
  337. ++i;
  338. } while (File.Exists(path));
  339. return path;
  340. }
  341. /// <summary>
  342. /// 检查文件夹是否重复 追加尾号
  343. /// </summary>
  344. /// <param name="path"></param>
  345. /// <returns></returns>
  346. public static string CreateFolder(string folder)
  347. {
  348. int i = 1;
  349. string oldDestName = folder;
  350. DirectoryInfo info = new DirectoryInfo(folder);
  351. do
  352. {
  353. info = new DirectoryInfo(folder);
  354. if (info.Exists)
  355. {
  356. string fileName = oldDestName;
  357. folder = fileName + string.Format(@"({0})", i);
  358. }
  359. ++i;
  360. } while (info.Exists);
  361. info.Create();
  362. return folder;
  363. }
  364. /// <summary>
  365. /// 将Document 返回的PageSize 转换成对应单位
  366. /// </summary>
  367. /// <param name="size"></param>
  368. /// <param name="unit"></param>
  369. /// <returns></returns>
  370. public static double GetUnitsFromPageSize(double size, PageItemUnits unit = PageItemUnits.MM)
  371. {
  372. double sizeWithUnit = 0;
  373. switch (unit)
  374. {
  375. case PageItemUnits.MM:
  376. sizeWithUnit = size / 72 * 25.4;
  377. break;
  378. case PageItemUnits.CM:
  379. sizeWithUnit = size / 72 * 25.4 / 10.0;
  380. break;
  381. case PageItemUnits.IN:
  382. sizeWithUnit = size / 72;
  383. break;
  384. default:
  385. break;
  386. }
  387. return sizeWithUnit;
  388. }
  389. /// <summary>
  390. /// 将mm单位转换成pdf文件尺寸
  391. /// </summary>
  392. /// <param name="size"></param>
  393. /// <returns></returns>
  394. public static double GetPageSizeFomrUnit(double size)
  395. {
  396. double pagesize = 0;
  397. pagesize = size / 25.4 * 72.0;
  398. return pagesize;
  399. }
  400. /// <summary>
  401. /// 返回设备DPI
  402. /// </summary>
  403. /// <returns></returns>
  404. public static double GetDpi()
  405. {
  406. BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.NonPublic;
  407. PropertyInfo property = typeof(SystemParameters).GetProperty("Dpi", bindingAttr);
  408. return (int)property.GetValue(null, null);
  409. }
  410. /// <summary>
  411. /// 根据路径计算文件大小
  412. /// </summary>
  413. /// <param name="path"></param>
  414. /// <returns></returns>
  415. public static string GetFileSize(string path)
  416. {
  417. System.IO.FileInfo fileInfo = null;
  418. try
  419. {
  420. fileInfo = new System.IO.FileInfo(path);
  421. }
  422. catch
  423. {
  424. return "0KB";
  425. }
  426. if (fileInfo != null && fileInfo.Exists)
  427. {
  428. var size = Math.Round(fileInfo.Length / 1024.0, 0);
  429. if (size > 1024)
  430. {
  431. var sizeDouble = Math.Round(size / 1024.0, 2);
  432. if (sizeDouble > 1024)
  433. {
  434. sizeDouble = Math.Round(sizeDouble / 1024.0, 2);
  435. return sizeDouble + "G";
  436. }
  437. else
  438. return sizeDouble + "M";
  439. }
  440. else
  441. {
  442. return (int)System.Math.Ceiling(size) + "KB";
  443. }
  444. }
  445. else
  446. {
  447. return "0KB";
  448. }
  449. }
  450. /// <summary>
  451. /// 将sdk里的日期转化为标准日期格式
  452. /// </summary>
  453. /// <param name="sdkDate"></param>
  454. /// <returns></returns>
  455. public static string GetDate(string sdkDate)
  456. {
  457. try
  458. {
  459. if (sdkDate == null || string.IsNullOrEmpty(sdkDate))
  460. {
  461. return "";
  462. }
  463. string dateStr = Regex.Match(sdkDate, "(?<=D\\:)[0-9]+(?=[\\+\\-])").Value;
  464. if (string.IsNullOrEmpty(dateStr))
  465. {
  466. return "";
  467. }
  468. string text = dateStr.Substring(0, 4) + "-" + dateStr.Substring(4, 2) + "-" + dateStr.Substring(6, 2) + " " + dateStr.Substring(8, 2) + ":" + dateStr.Substring(10, 2) + ":" + dateStr.Substring(12, 2);
  469. return text;
  470. }
  471. catch { return ""; }
  472. }
  473. }
  474. }