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.

1038 lines
37 KiB

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