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.

1035 lines
37 KiB

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