CommonHelper.cs 14 KB

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