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

997 lines
36 KiB

  1. using Apewer.Internals.Interop;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Drawing;
  5. using System.IO;
  6. using System.Runtime.InteropServices;
  7. using System.Security;
  8. using System.Reflection;
  9. #if NETFX || NETCORE
  10. using System.Drawing.Drawing2D;
  11. using System.Drawing.Imaging;
  12. using System.Drawing.Text;
  13. using System.Windows.Forms;
  14. #endif
  15. namespace Apewer.Surface
  16. {
  17. /// <summary>窗体实用工具。</summary>
  18. [SecuritySafeCritical]
  19. public class FormsUtility
  20. {
  21. /// <summary>线程锁。</summary>
  22. public static object ThreadLocker = new object();
  23. #if NETFX || NETCORE
  24. /// <summary>窗体启动初始化。</summary>
  25. [STAThread]
  26. public static void StartInitialization()
  27. {
  28. Control.CheckForIllegalCrossThreadCalls = false;
  29. Application.EnableVisualStyles();
  30. Application.SetCompatibleTextRenderingDefault(false);
  31. }
  32. /// <summary>禁用跨线程调用检查。</summary>
  33. public static void CrossThread()
  34. {
  35. Control.CheckForIllegalCrossThreadCalls = false;
  36. }
  37. #endif
  38. #region 颜色。
  39. /// <summary>获取所有可枚举的颜色。</summary>
  40. public static Color[] EnumerableColor
  41. {
  42. get
  43. {
  44. var list = new List<Color>();
  45. list.Add(Color.AliceBlue);
  46. list.Add(Color.AntiqueWhite);
  47. list.Add(Color.Aqua);
  48. list.Add(Color.Aquamarine);
  49. list.Add(Color.Azure);
  50. list.Add(Color.Beige);
  51. list.Add(Color.Bisque);
  52. list.Add(Color.Black);
  53. list.Add(Color.BlanchedAlmond);
  54. list.Add(Color.Blue);
  55. list.Add(Color.BlueViolet);
  56. list.Add(Color.Brown);
  57. list.Add(Color.BurlyWood);
  58. list.Add(Color.CadetBlue);
  59. list.Add(Color.Chartreuse);
  60. list.Add(Color.Chocolate);
  61. list.Add(Color.Coral);
  62. list.Add(Color.CornflowerBlue);
  63. list.Add(Color.Cornsilk);
  64. list.Add(Color.Crimson);
  65. list.Add(Color.Cyan);
  66. list.Add(Color.DarkBlue);
  67. list.Add(Color.DarkCyan);
  68. list.Add(Color.DarkGoldenrod);
  69. list.Add(Color.DarkGray);
  70. list.Add(Color.DarkGreen);
  71. list.Add(Color.DarkKhaki);
  72. list.Add(Color.DarkMagenta);
  73. list.Add(Color.DarkOliveGreen);
  74. list.Add(Color.DarkOrange);
  75. list.Add(Color.DarkOrchid);
  76. list.Add(Color.DarkRed);
  77. list.Add(Color.DarkSalmon);
  78. list.Add(Color.DarkSeaGreen);
  79. list.Add(Color.DarkSlateBlue);
  80. list.Add(Color.DarkSlateGray);
  81. list.Add(Color.DarkTurquoise);
  82. list.Add(Color.DarkViolet);
  83. list.Add(Color.DeepPink);
  84. list.Add(Color.DeepSkyBlue);
  85. list.Add(Color.DimGray);
  86. list.Add(Color.DodgerBlue);
  87. list.Add(Color.Firebrick);
  88. list.Add(Color.FloralWhite);
  89. list.Add(Color.ForestGreen);
  90. list.Add(Color.Fuchsia);
  91. list.Add(Color.Gainsboro);
  92. list.Add(Color.GhostWhite);
  93. list.Add(Color.Gold);
  94. list.Add(Color.Goldenrod);
  95. list.Add(Color.Gray);
  96. list.Add(Color.Green);
  97. list.Add(Color.GreenYellow);
  98. list.Add(Color.Honeydew);
  99. list.Add(Color.HotPink);
  100. list.Add(Color.IndianRed);
  101. list.Add(Color.Indigo);
  102. list.Add(Color.Ivory);
  103. list.Add(Color.Khaki);
  104. list.Add(Color.Lavender);
  105. list.Add(Color.LavenderBlush);
  106. list.Add(Color.LawnGreen);
  107. list.Add(Color.LemonChiffon);
  108. list.Add(Color.LightBlue);
  109. list.Add(Color.LightCoral);
  110. list.Add(Color.LightCyan);
  111. list.Add(Color.LightGoldenrodYellow);
  112. list.Add(Color.LightGray);
  113. list.Add(Color.LightGreen);
  114. list.Add(Color.LightPink);
  115. list.Add(Color.LightSalmon);
  116. list.Add(Color.LightSeaGreen);
  117. list.Add(Color.LightSkyBlue);
  118. list.Add(Color.LightSlateGray);
  119. list.Add(Color.LightSteelBlue);
  120. list.Add(Color.LightYellow);
  121. list.Add(Color.Lime);
  122. list.Add(Color.LimeGreen);
  123. list.Add(Color.Linen);
  124. list.Add(Color.Magenta);
  125. list.Add(Color.Maroon);
  126. list.Add(Color.MediumAquamarine);
  127. list.Add(Color.MediumBlue);
  128. list.Add(Color.MediumOrchid);
  129. list.Add(Color.MediumPurple);
  130. list.Add(Color.MediumSeaGreen);
  131. list.Add(Color.MediumSlateBlue);
  132. list.Add(Color.MediumSpringGreen);
  133. list.Add(Color.MediumTurquoise);
  134. list.Add(Color.MediumVioletRed);
  135. list.Add(Color.MidnightBlue);
  136. list.Add(Color.MintCream);
  137. list.Add(Color.MistyRose);
  138. list.Add(Color.Moccasin);
  139. list.Add(Color.NavajoWhite);
  140. list.Add(Color.Navy);
  141. list.Add(Color.OldLace);
  142. list.Add(Color.Olive);
  143. list.Add(Color.OliveDrab);
  144. list.Add(Color.Orange);
  145. list.Add(Color.OrangeRed);
  146. list.Add(Color.Orchid);
  147. list.Add(Color.PaleGoldenrod);
  148. list.Add(Color.PaleGreen);
  149. list.Add(Color.PaleTurquoise);
  150. list.Add(Color.PaleVioletRed);
  151. list.Add(Color.PapayaWhip);
  152. list.Add(Color.PeachPuff);
  153. list.Add(Color.Peru);
  154. list.Add(Color.Pink);
  155. list.Add(Color.Plum);
  156. list.Add(Color.PowderBlue);
  157. list.Add(Color.Purple);
  158. list.Add(Color.Red);
  159. list.Add(Color.RosyBrown);
  160. list.Add(Color.RoyalBlue);
  161. list.Add(Color.SaddleBrown);
  162. list.Add(Color.Salmon);
  163. list.Add(Color.SandyBrown);
  164. list.Add(Color.SeaGreen);
  165. list.Add(Color.SeaShell);
  166. list.Add(Color.Sienna);
  167. list.Add(Color.Silver);
  168. list.Add(Color.SkyBlue);
  169. list.Add(Color.SlateBlue);
  170. list.Add(Color.SlateGray);
  171. list.Add(Color.Snow);
  172. list.Add(Color.SpringGreen);
  173. list.Add(Color.SteelBlue);
  174. list.Add(Color.Tan);
  175. list.Add(Color.Teal);
  176. list.Add(Color.Thistle);
  177. list.Add(Color.Tomato);
  178. //list.Add(Color.Transparent);
  179. list.Add(Color.Turquoise);
  180. list.Add(Color.Violet);
  181. list.Add(Color.Wheat);
  182. list.Add(Color.White);
  183. list.Add(Color.WhiteSmoke);
  184. list.Add(Color.Yellow);
  185. list.Add(Color.YellowGreen);
  186. return list.ToArray();
  187. }
  188. }
  189. /// <summary>用于填充背景色。</summary>
  190. public static Color GraceWall { get { return Color.FromArgb(0xff, 0xf7, 0xf7, 0xf7); } }
  191. /// <summary>用于控件边框。</summary>
  192. public static Color GraceBorder { get { return Color.FromArgb(0xff, 0xdf, 0xdf, 0xdf); } }
  193. /// <summary>用于无效的文本、备注文本。</summary>
  194. public static Color GraceLocked { get { return Color.FromArgb(0xff, 0x7f, 0x7f, 0x7f); } }
  195. /// <summary>用于次级文本。</summary>
  196. public static Color GraceMinor { get { return Color.FromArgb(0xff, 0x3f, 0x3f, 0x3f); } }
  197. /// <summary>用于焦点状态的控件边框。</summary>
  198. public static Color GraceSilver { get { return Color.FromArgb(0xff, 0xbf, 0xbf, 0xbf); } }
  199. /// <summary>系统定义的颜色。</summary>
  200. public static Color Transparent { get { return Color.Transparent; } }
  201. /// <summary>系统定义的颜色。</summary>
  202. public static Color Black { get { return Color.Black; } }
  203. /// <summary>系统定义的颜色。</summary>
  204. public static Color White { get { return Color.White; } }
  205. /// <summary>系统定义的颜色。</summary>
  206. public static Color Gray { get { return Color.Gray; } }
  207. /// <summary>系统定义的颜色。</summary>
  208. public static Color DarkGray { get { return Color.DarkGray; } }
  209. /// <summary>系统定义的颜色。</summary>
  210. public static Color LightGray { get { return Color.LightGray; } }
  211. /// <summary>系统定义的颜色。</summary>
  212. public static Color Red { get { return Color.Red; } }
  213. /// <summary>系统定义的颜色。</summary>
  214. public static Color Green { get { return Color.Green; } }
  215. /// <summary>系统定义的颜色。</summary>
  216. public static Color Blue { get { return Color.Blue; } }
  217. /// <summary>系统定义的颜色。</summary>
  218. public static Color Orange { get { return Color.DarkOrange; } }
  219. /// <summary>系统定义的颜色。</summary>
  220. public static Color Purple { get { return Color.Purple; } }
  221. /// <summary>随机主题色。</summary>
  222. public static Color RandomColor
  223. {
  224. get { var colors = EnumerableColor; return colors[NumberUtility.RandomInteger(colors.Length - 1)]; }
  225. }
  226. /// <summary>计算 Alpha 合成颜色(基色),基色均需计算。</summary>
  227. /// <param name="alpha">前景色 Alpha 值。</param>
  228. /// <param name="back">背景色(基色)。</param>
  229. /// <param name="fore">前景色(基色)。</param>
  230. /// <param name="depth">颜色深度,最大值。</param>
  231. /// <returns>合成后的颜色(基色)。</returns>
  232. public static int MixAlpha(int alpha, int fore, int back, int depth = 255)
  233. {
  234. int b = back, f = fore;
  235. if (b > depth) b = depth; if (b < 0) b = 0;
  236. if (f > depth) f = depth; if (f < 0) f = 0;
  237. int v = fore * alpha / depth + back * (depth - alpha) / depth;
  238. if (v > depth) v = depth; if (v < 0) v = 0;
  239. return v;
  240. }
  241. /// <summary>按 Alpha 混合不透明的颜色。</summary>
  242. /// <param name="backColor">背景色。</param>
  243. /// <param name="foreColor">前景色。</param>
  244. /// <param name="foreAlpha">前景 Alpha 值。</param>
  245. /// <returns>混合后的颜色。</returns>
  246. public static Color MixAlpha(Color backColor, Color foreColor, int foreAlpha)
  247. {
  248. var r = MixAlpha(backColor.R, foreColor.R, foreAlpha);
  249. var g = MixAlpha(backColor.G, foreColor.G, foreAlpha);
  250. var b = MixAlpha(backColor.B, foreColor.B, foreAlpha);
  251. var a = MixAlpha(backColor.A, foreColor.A, foreAlpha);
  252. return Color.FromArgb(a, r, g, b);
  253. }
  254. #endregion
  255. #region 屏幕。
  256. #if NETFX || NETCORE
  257. /// <summary>获取屏幕的截图。</summary>
  258. public static Bitmap[] ScreenShot()
  259. {
  260. var list = new List<Bitmap>();
  261. var all = Screen.AllScreens;
  262. foreach (var screen in all)
  263. {
  264. int vw = screen.Bounds.Width;
  265. int vh = screen.Bounds.Height;
  266. int vd = screen.BitsPerPixel;
  267. Bitmap b = new Bitmap(vw, vh, PixelFormat.Format32bppArgb);
  268. Graphics g = Graphics.FromImage(b);
  269. g.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(vw, vh));
  270. g.Dispose();
  271. list.Add(b);
  272. }
  273. return list.ToArray();
  274. }
  275. /// <summary>获取指定屏幕的截图。</summary>
  276. /// <param name="screen">屏幕号。</param>
  277. internal static Bitmap ScreenShot(int screen)
  278. {
  279. var a = Screen.AllScreens;
  280. if ((a.Length > 0) && (screen >= 0) && (screen < a.Length))
  281. {
  282. try
  283. {
  284. int w = a[screen].Bounds.Width;
  285. int h = a[screen].Bounds.Height;
  286. int d = a[screen].BitsPerPixel;
  287. Bitmap b = new Bitmap(w, h, PixelFormat.Format32bppArgb);
  288. Graphics g = Graphics.FromImage(b);
  289. g.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(w, h));
  290. g.Dispose();
  291. return b;
  292. }
  293. catch { }
  294. }
  295. return new Bitmap(0, 0, PixelFormat.Format32bppArgb);
  296. }
  297. /// <summary>获取指定屏幕的截图。</summary>
  298. /// <param name="screen">屏幕,若为 Null 则选择主屏幕。</param>
  299. internal static Bitmap ScreenShot(Screen screen)
  300. {
  301. if (screen == null)
  302. {
  303. try
  304. {
  305. int w = Screen.PrimaryScreen.Bounds.Width;
  306. int h = Screen.PrimaryScreen.Bounds.Height;
  307. int d = Screen.PrimaryScreen.BitsPerPixel;
  308. Bitmap b = new Bitmap(w, h, PixelFormat.Format32bppArgb);
  309. Graphics g = Graphics.FromImage(b);
  310. g.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(w, h));
  311. g.Dispose();
  312. return b;
  313. }
  314. catch { }
  315. }
  316. return new Bitmap(0, 0, PixelFormat.Format32bppArgb);
  317. }
  318. #endif
  319. #endregion
  320. #region 窗体。
  321. #if NETFX || NETCORE
  322. /// <summary>移动窗体。</summary>
  323. public static void MoveForm(Form form)
  324. {
  325. if (form != null) MoveForm(form.Handle);
  326. }
  327. /// <summary>移动窗体。</summary>
  328. public static void MoveForm(IntPtr form)
  329. {
  330. User32.ReleaseCapture();
  331. User32.SendMessage(form, 0x112, new IntPtr(Constant.SC_MOVE + 2), new IntPtr(0));
  332. }
  333. /// <summary>启用鼠标穿透。</summary>
  334. public static void MousePenetration(Form form)
  335. {
  336. if (form != null) MousePenetration(form.Handle);
  337. }
  338. /// <summary>启用鼠标穿透。</summary>
  339. public static void MousePenetration(IntPtr form)
  340. {
  341. int intExTemp = User32.GetWindowLong(form, Constant.GWL_EXSTYLE);
  342. int oldGWLEx = User32.SetWindowLong(form, Constant.GWL_EXSTYLE, Constant.WS_EX_TRANSPARENT | Constant.WS_EX_LAYERED);
  343. }
  344. /// <summary>将窗体最大化,不覆盖任务栏。</summary>
  345. /// <param name="form">窗体。</param>
  346. public static void ToMaximum(Form form)
  347. {
  348. if (form != null)
  349. {
  350. var s = Screen.FromControl(form);
  351. var r = s.WorkingArea;
  352. if ((form.MaximumSize.Width < r.Width) || (form.MaximumSize.Height < r.Height))
  353. {
  354. form.MaximumSize = r.Size;
  355. }
  356. form.Location = r.Location;
  357. form.Size = r.Size;
  358. }
  359. }
  360. /// <summary>用指定图像绘制窗体,窗体与图像的大小必须一致。</summary>
  361. /// <param name="form">要绘制的窗体。</param>
  362. /// <param name="image">要使用的图像。</param>
  363. public static void UpdateShadow(Form form, Image image)
  364. {
  365. if ((form != null) && (image != null))
  366. {
  367. Bitmap vbitmap;
  368. if ((form.Width != image.Width) || (form.Height != image.Height))
  369. {
  370. vbitmap = new Bitmap(image.GetThumbnailImage(form.Width, form.Height, null, IntPtr.Zero));
  371. }
  372. else
  373. {
  374. vbitmap = new Bitmap(image);
  375. }
  376. var screendc = User32.GetDC(IntPtr.Zero);
  377. var location = new Internals.Interop.Point(form.Left, form.Top);
  378. var size = new Internals.Interop.Size(form.Width, form.Height);
  379. var compatibledc = Gdi32.CreateCompatibleDC(screendc);
  380. var handle = vbitmap.GetHbitmap(Color.FromArgb(0));
  381. var oldbitmap = Gdi32.SelectObject(compatibledc, handle);
  382. var srcloc = new Internals.Interop.Point(0, 0);
  383. var blendfunction = new BlendFunction();
  384. blendfunction.blendop = Constant.AC_SRC_OVER;
  385. blendfunction.sourceconstantalpha = byte.Parse("255");
  386. blendfunction.alphaformat = Constant.AC_SRC_ALPHA;
  387. blendfunction.blendflags = 0;
  388. User32.UpdateLayeredWindow(form.Handle, screendc, ref location, ref size, compatibledc, ref srcloc, 0, ref blendfunction, Constant.ULW_ALPHA);
  389. if (handle != IntPtr.Zero)
  390. {
  391. Gdi32.SelectObject(compatibledc, oldbitmap);
  392. Gdi32.DeleteObject(handle);
  393. }
  394. User32.ReleaseDC(IntPtr.Zero, screendc);
  395. Gdi32.DeleteDC(compatibledc);
  396. }
  397. }
  398. /// <summary>为窗体启用阴影。</summary>
  399. /// <param name="form">要启用阴影的窗体。</param>
  400. public static void EnableShadow(Form form)
  401. {
  402. if (form == null) return;
  403. int vformclass = User32.GetClassLong(form.Handle, Constant.GCL_STYLE);
  404. User32.SetClassLong(form.Handle, Constant.GCL_STYLE, vformclass | Constant.CS_DROPSHADOW);
  405. }
  406. /// <summary>恢复任务栏中窗体标题的右键菜单。</summary>
  407. public static void SetTaskMenu(Form form)
  408. {
  409. if (form != null)
  410. {
  411. var hwnd = form.Handle;
  412. var href = new HandleRef(form, hwnd);
  413. int windowLong = (User32.GetWindowLong(hwnd, -16));
  414. User32.SetWindowLong(hwnd, -16, windowLong | Constant.WS_SYSMENU | Constant.WS_MINIMIZEBOX);
  415. }
  416. }
  417. #endif
  418. #endregion
  419. #region 控件。
  420. #if NETFX || NETCORE
  421. /// <summary>在主界面中移动控件,由目标控件取代当前控件,形成切换控件的动画。</summary>
  422. /// <param name="current">当前显示的控件。</param>
  423. /// <param name="target">将要显示的目标控件。</param>
  424. public static void AnimateGoPanel(Control current, Control target)
  425. {
  426. AnimateGoPanel(current.Location, current.Size, 0, 10, current, target, true);
  427. }
  428. /// <summary>在主界面中移动控件,由目标控件取代当前控件,形成切换控件的动画。</summary>
  429. /// <param name="current">当前显示的控件。</param>
  430. /// <param name="target">将要显示的目标控件。</param>
  431. /// <param name="next">向左移动。</param>
  432. public static void AnimateGoPanel(Control current, Control target, bool next)
  433. {
  434. AnimateGoPanel(current.Location, current.Size, 0, 10, current, target, next);
  435. }
  436. /// <summary>在主界面中移动控件,由目标控件取代当前控件,形成切换控件的动画。</summary>
  437. /// <param name="point">控件左上角坐标。</param>
  438. /// <param name="size">控件大小。</param>
  439. /// <param name="span">当前控件和目标控件的间距,若值小于 0 则更正为 0 。</param>
  440. /// <param name="frame">移动的次数,若值小于 0 则更正为 20。</param>
  441. /// <param name="current">当前显示的控件。</param>
  442. /// <param name="target">将要显示的目标控件。</param>
  443. /// <param name="next">向左移动。</param>
  444. public static void AnimateGoPanel(System.Drawing.Point point, System.Drawing.Size size, int span, int frame, Control current, Control target, bool next = true)
  445. {
  446. int s = (span < 0) ? span : 0;
  447. int step = (current.Width + s) / ((frame < 1) ? 20 : frame);
  448. int x = point.X;
  449. int y = point.Y;
  450. current.Size = size;
  451. target.Size = size;
  452. current.Location = point;
  453. if (next)
  454. {
  455. target.Location = new System.Drawing.Point(size.Width, point.Y);
  456. current.Visible = true;
  457. target.Visible = true;
  458. Application.DoEvents();
  459. while (target.Left > x)
  460. {
  461. s = ((target.Left - x) < step) ? (target.Left - x) : step;
  462. target.Left -= s;
  463. current.Left -= s;
  464. Application.DoEvents();
  465. System.Threading.Thread.Sleep(1);
  466. }
  467. }
  468. else
  469. {
  470. target.Location = new System.Drawing.Point(x - size.Width, x);
  471. current.Visible = true;
  472. target.Visible = true;
  473. Application.DoEvents();
  474. while (target.Left < x)
  475. {
  476. s = ((x - target.Left) < step) ? x - target.Left : step;
  477. target.Left += s;
  478. current.Left += s;
  479. Application.DoEvents();
  480. System.Threading.Thread.Sleep(1);
  481. }
  482. }
  483. current.Visible = false;
  484. }
  485. /// <summary></summary>
  486. public static void Invoke(Control control, Action action, bool async = false)
  487. {
  488. if (control == null || action == null) return;
  489. // control.Invoke(action);
  490. if (async)
  491. {
  492. control.BeginInvoke(new Action(delegate ()
  493. {
  494. action.Invoke();
  495. }));
  496. }
  497. else
  498. {
  499. control.Invoke(new Action(delegate ()
  500. {
  501. action.Invoke();
  502. }));
  503. }
  504. }
  505. /// <summary></summary>
  506. public static void BeginInvoke(Control control, Action action)
  507. {
  508. if (control == null || action == null) return;
  509. control.BeginInvoke(new Action(delegate ()
  510. {
  511. action.Invoke();
  512. }));
  513. }
  514. /// <summary>设置窗体置顶。</summary>
  515. public static void SetTopMost(IntPtr form, bool value = true)
  516. {
  517. if (form == null || form == IntPtr.Zero) return;
  518. User32.SetWindowPos(form, new IntPtr(value ? -1 : -2), 0, 0, 0, 0, 3);
  519. }
  520. /// <summary>设置窗体置顶。</summary>
  521. public static void SetTopMost(Form form, bool value = true)
  522. {
  523. if (form != null) SetTopMost(form.Handle, value);
  524. }
  525. #endif
  526. #endregion
  527. #region 绘图。
  528. #if NETFX || NETCORE
  529. /// <summary>绘制内边框。</summary>
  530. /// <param name="image">源图像。</param>
  531. /// <param name="border">边框颜色。</param>
  532. public static bool PaintBorder(ref Image image, Color border)
  533. {
  534. if (image != null)
  535. {
  536. var g = Graphics.FromImage(image);
  537. var p = new Pen(border);
  538. g.DrawRectangle(p, 0, 0, image.Width - 1, image.Height - 1);
  539. p.Dispose();
  540. g.Dispose();
  541. return true;
  542. }
  543. else return false;
  544. }
  545. /// <summary>绘制内边框。</summary>
  546. /// <param name="image">源图像。</param>
  547. /// <param name="border">边框颜色。</param>
  548. public static bool PaintBorder(ref Bitmap image, Color border)
  549. {
  550. if (image != null)
  551. {
  552. var g = Graphics.FromImage(image);
  553. var p = new Pen(border);
  554. g.DrawRectangle(p, 0, 0, image.Width - 1, image.Height - 1);
  555. p.Dispose();
  556. g.Dispose();
  557. return true;
  558. }
  559. else return false;
  560. }
  561. /// <summary>绘制内边框。</summary>
  562. /// <param name="image">源图像。</param>
  563. /// <param name="border">边框颜色。</param>
  564. /// <param name="wall">背景颜色。</param>
  565. public static bool PaintBorder(ref Image image, Color border, Color wall)
  566. {
  567. if (image != null)
  568. {
  569. var g = Graphics.FromImage(image);
  570. var p = new Pen(border);
  571. g.Clear(wall);
  572. g.DrawRectangle(p, 0, 0, image.Width - 1, image.Height - 1);
  573. p.Dispose();
  574. g.Dispose();
  575. return true;
  576. }
  577. else return false;
  578. }
  579. /// <summary>建立带有圆角样式的路径。</summary>
  580. /// <param name="rect">建立矩形路径的区域。</param>
  581. /// <param name="radius">圆角的大小。</param>
  582. /// <returns>建立的路径。</returns>
  583. public static GraphicsPath CreatePath(Rectangle rect, int radius = 0)
  584. {
  585. GraphicsPath path = new GraphicsPath();
  586. int r = (radius < 0) ? 0 : radius;
  587. switch (r)
  588. {
  589. case 0:
  590. path.AddRectangle(rect);
  591. break;
  592. default:
  593. path.AddArc(rect.X, rect.Y, r, r, 180, 90);
  594. path.AddArc(rect.Right - r - 1, rect.Y, r, r, 270, 90);
  595. path.AddArc(rect.Right - r - 1, rect.Bottom - r - 1, r, r, 0, 90);
  596. path.AddArc(rect.X, rect.Bottom - r - 1, r, r, 90, 90);
  597. break;
  598. }
  599. path.CloseFigure();
  600. return path;
  601. }
  602. /// <summary></summary>
  603. /// <param name="location"></param>
  604. /// <param name="size"></param>
  605. /// <param name="radius"></param>
  606. /// <returns></returns>
  607. public static GraphicsPath GetRadiusPath(PointF location, SizeF size, float radius)
  608. {
  609. var loc = location;
  610. var rds = Math.Abs(radius);
  611. var path = new GraphicsPath();
  612. float x, y, r;
  613. r = rds * 2;
  614. // 左上角。
  615. x = loc.X;
  616. y = loc.Y;
  617. path.AddArc(x, y, r, r, 180, 90);
  618. // 右上角。
  619. x = loc.X + size.Width - rds * 2;
  620. y = loc.Y;
  621. path.AddArc(x, y, r, r, 270, 90);
  622. // 左下角。
  623. x = loc.X;
  624. y = loc.Y + size.Height - rds * 2;
  625. path.AddArc(x, y, r, r, 0, 90);
  626. // 右下角。
  627. x = loc.X + size.Width - rds * 2;
  628. y = loc.Y + size.Height - rds * 2;
  629. path.AddArc(x, y, r, r, 90, 90);
  630. // 边框直线:上、下、左、右。
  631. path.AddLine((float)(loc.X + rds), (float)loc.Y, (float)(loc.X + size.Width - rds), (float)loc.Y);
  632. path.AddLine((float)(loc.X + rds), (float)(loc.Y + size.Height), (float)(loc.X + size.Width - rds), (float)(loc.Y + size.Height));
  633. path.AddLine((float)loc.X, (float)(loc.Y + rds), (float)loc.X, (float)(loc.Y + size.Height - rds));
  634. path.AddLine((float)(loc.X + size.Width), (float)(loc.Y + rds), (float)(loc.X + size.Width), (float)(loc.Y + size.Height - rds));
  635. return path;
  636. }
  637. /// <summary>获取指定文件中的图标总数。</summary>
  638. public static int GetIconsCount(string path)
  639. {
  640. if (!File.Exists(path)) return 0;
  641. var count = User32.PrivateExtractIcons(path, 0, 0, 0, null, null, 0, 0);
  642. return count;
  643. }
  644. /// <summary>获取指定文件中的图标。</summary>
  645. public static Bitmap[] GetIconsBitmap(string path = null, int size = 256)
  646. {
  647. if (string.IsNullOrEmpty(path)) path = Application.ExecutablePath;
  648. if (!File.Exists(path)) return null;
  649. var count = User32.PrivateExtractIcons(path, 0, 0, 0, null, null, 0, 0);
  650. var ptrs = new IntPtr[count];
  651. var ids = new int[count];
  652. var succeed = User32.PrivateExtractIcons(path, 0, size, size, ptrs, ids, count, 0);
  653. var images = new Bitmap[count];
  654. for (var i = 0; i < succeed; i++)
  655. {
  656. if (ptrs[i] == IntPtr.Zero) continue;
  657. using (var icon = Icon.FromHandle(ptrs[i]))
  658. {
  659. var bitmap = icon.ToBitmap();
  660. images[i] = bitmap;
  661. }
  662. User32.DestroyIcon(ptrs[i]);
  663. }
  664. return images;
  665. }
  666. /// <summary>从文件获取图标。</summary>
  667. public static Icon GetExecutableIcon(string path)
  668. {
  669. try { return Icon.ExtractAssociatedIcon(path); }
  670. catch { return null; }
  671. }
  672. #endif
  673. #endregion
  674. #region 字体。
  675. private const string FontYahei = "Microsoft Yahei";
  676. private const string FontSimsun = "Simsun";
  677. private static string _fontname = "";
  678. /// <summary>存在微软雅黑字体。</summary>
  679. public static bool MsyhExist
  680. {
  681. get { return File.Exists("c:\\windows\\fonts\\msyh.ttc"); }
  682. }
  683. /// <summary>获取默认字体名称。</summary>
  684. public static string DefaultFontName
  685. {
  686. get
  687. {
  688. if (!string.IsNullOrEmpty(_fontname)) return _fontname;
  689. try
  690. {
  691. if (File.Exists("c:\\windows\\fonts\\msyh.ttc")) return FontYahei;
  692. else return FontSimsun;
  693. }
  694. catch { return FontSimsun; }
  695. }
  696. }
  697. #if NETFX || NETCORE
  698. /// <summary>获取默认字体。</summary>
  699. public static Font DefaultFont
  700. {
  701. get { return new Font(DefaultFontName, 9); }
  702. }
  703. /// <summary>获取大小为 9 的默认字体。</summary>
  704. public static Font NewFont()
  705. {
  706. return new Font(DefaultFontName, 9);
  707. }
  708. /// <summary>获取指定大小的默认字体。</summary>
  709. public static Font NewFont(float size)
  710. {
  711. return new Font(DefaultFontName, size);
  712. }
  713. /// <summary>获取指定大小的默认字体。</summary>
  714. public static Font NewFont(float size, bool bold)
  715. {
  716. return new Font(DefaultFontName, size, bold ? FontStyle.Bold : FontStyle.Regular);
  717. }
  718. /// <summary>从文件加载字体,并获取指定字体。</summary>
  719. /// <param name="path">文件路径。</param>
  720. /// <param name="index">文件中的 Font Family 索引,默认取第一个(索引 0)。</param>
  721. /// <returns>已存在的 Font Family,如果指定的索引处不存在 Font Family,则返回 NULL 值。</returns>
  722. public static FontFamily LoadFont(string path, int index = 0)
  723. {
  724. if (index < 0) return null;
  725. if (string.IsNullOrEmpty(path)) return null;
  726. if (!File.Exists(path)) return null;
  727. try
  728. {
  729. var pfc = new PrivateFontCollection();
  730. pfc.AddFontFile(path);
  731. var fs = pfc.Families;
  732. if (fs.Length > 0 && index < fs.Length) return fs[index];
  733. }
  734. catch { }
  735. return null;
  736. }
  737. #if NET40 || NET461
  738. /// <summary></summary>
  739. public static List<System.Windows.Media.FontFamily> ListFileFont(string path)
  740. {
  741. try
  742. {
  743. var collection = System.Windows.Media.Fonts.GetFontFamilies(path);
  744. var list = new List<System.Windows.Media.FontFamily>(collection.Count);
  745. foreach (var item in collection) list.Add(item);
  746. return list;
  747. }
  748. catch { }
  749. return new List<System.Windows.Media.FontFamily>();
  750. }
  751. /// <summary></summary>
  752. public static List<System.Windows.Media.FontFamily> ListSystemFont()
  753. {
  754. var collection = System.Windows.Media.Fonts.SystemFontFamilies;
  755. var list = new List<System.Windows.Media.FontFamily>(collection.Count);
  756. foreach (var item in collection) list.Add(item);
  757. return list;
  758. }
  759. /// <summary>枚举指定字体中的所有字符。</summary>
  760. public static List<char> EnumerateFontChars(IEnumerable<System.Windows.Media.Typeface> typefaces)
  761. {
  762. var chars = new List<char>();
  763. if (typefaces != null)
  764. {
  765. foreach (var typeface in typefaces)
  766. {
  767. var subs = EnumerateFontChars(typeface);
  768. if (subs != null) chars.AddRange(subs);
  769. }
  770. }
  771. return chars;
  772. }
  773. /// <summary>枚举指定字体中的所有字符。</summary>
  774. public static List<char> EnumerateFontChars(System.Windows.Media.Typeface typeface)
  775. {
  776. System.Windows.Media.GlyphTypeface glyph;
  777. var tried = typeface.TryGetGlyphTypeface(out glyph);
  778. if (glyph == null) return null;
  779. var map = glyph.CharacterToGlyphMap;
  780. var keys = map.Keys;
  781. var chars = new List<char>(keys.Count);
  782. for (int i = 0; i < keys.Count; i++)
  783. {
  784. var index = System.Linq.Enumerable.ElementAt(keys, i);
  785. try
  786. {
  787. var c = Convert.ToChar(index);
  788. chars.Add(c.ToString());
  789. }
  790. catch { }
  791. }
  792. return chars;
  793. }
  794. #endif
  795. /// <summary>获取已安装的字体。</summary>
  796. public static List<FontFamily> ListInstalledFonts()
  797. {
  798. var list = new List<FontFamily>();
  799. int ret = 0; // Win32 API 返回值,非零值均为异常。
  800. // 初始化 FontCollection。
  801. var collection = new Internals.FontCollection();
  802. ret = GdiPlus.GdipNewInstalledFontCollection(out collection.NativePointer);
  803. if (ret != 0) return list;
  804. // 获取字体总数。
  805. int found1 = 0;
  806. ret = GdiPlus.GdipGetFontCollectionFamilyCount(new HandleRef(collection, collection.NativePointer), out found1);
  807. if (ret != 0) return list;
  808. // 获取字体指针。
  809. var ptrs = new IntPtr[found1];
  810. int found2 = 0;
  811. ret = GdiPlus.GdipGetFontCollectionFamilyList(new HandleRef(collection, collection.NativePointer), found1, ptrs, out found2);
  812. if (ret != 0) return list;
  813. // 获取字体列表。
  814. list.Capacity = found2;
  815. for (int i = 0; i < found2; i++)
  816. {
  817. IntPtr cloned;
  818. GdiPlus.GdipCloneFontFamily(new HandleRef(null, ptrs[i]), out cloned);
  819. try
  820. {
  821. var flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance;
  822. var args = new object[] { cloned };
  823. var instance = Activator.CreateInstance(typeof(FontFamily), flags, null, args, null, null);
  824. var item = instance as FontFamily;
  825. if (item != null) list.Add(item);
  826. }
  827. catch { }
  828. }
  829. list.Capacity = list.Count;
  830. return list;
  831. }
  832. private static bool GlyphExists(char c, Font font)
  833. {
  834. using (var dummy = Graphics.FromImage(new Bitmap(1, 1)))
  835. {
  836. IntPtr hdc = dummy.GetHdc();
  837. var pgi = new ushort[1];
  838. try
  839. {
  840. IntPtr hfont = font.ToHfont();
  841. Gdi32.SelectObject(hdc, hfont);
  842. string str = c.ToString();
  843. Gdi32.GetGlyphIndices(hdc, str, str.Length, pgi, Constant.GGI_MARK_NONEXISTING_GLYPHS);
  844. }
  845. catch { }
  846. dummy.ReleaseHdc(hdc);
  847. // 0xFFFF 表示字形不存在。
  848. return (pgi[0] != 0xffff);
  849. }
  850. }
  851. #endif
  852. #endregion
  853. }
  854. }