AppHelper.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. using DevExpress.LookAndFeel;
  2. using DevExpress.XtraRichEdit.Model;
  3. using DW5S.Repostory;
  4. using DxHelper;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.Drawing;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Reflection;
  14. using System.Runtime.InteropServices;
  15. using System.Runtime.Loader;
  16. using System.Security;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Windows.Forms;
  21. using System.Windows.Interop;
  22. namespace DW5S.App;
  23. public class AppHelper
  24. {
  25. public const string CultureName = "zh-CN";
  26. public static void InitAppSettings()
  27. {
  28. Application.ThreadException += Application_ThreadException;
  29. Application.EnableVisualStyles();
  30. Application.SetCompatibleTextRenderingDefault(false);
  31. Application.SetHighDpiMode(HighDpiMode.SystemAware);
  32. ChsLocalizer.UseChs();
  33. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
  34. AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
  35. DevExpress.Utils.AppearanceObject.DefaultFont = new System.Drawing.Font("微软雅黑", 9);
  36. DevExpress.Skins.SkinManager.EnableFormSkins();
  37. Application.ApplicationExit += (sender, e) =>
  38. {
  39. AppConfigHelper.SetAppSetting("SkinName", UserLookAndFeel.Default.ActiveSkinName);
  40. AppConfigHelper.SetAppSetting("PaletteName", UserLookAndFeel.Default.ActiveSvgPaletteName);
  41. AppConfigHelper.SetAppSetting("CompactMode", UserLookAndFeel.Default.CompactUIModeForced);
  42. };
  43. string skinName = AppConfigHelper.Get("SkinName","WXI");
  44. string paletteName = AppConfigHelper.Get("PaletteName");
  45. bool compactMode = AppConfigHelper.Get("CompactMode",true);
  46. if (compactMode)
  47. UserLookAndFeel.ForceCompactUIMode(true, false);
  48. if (!string.IsNullOrEmpty(paletteName))
  49. UserLookAndFeel.Default.SetSkinStyle(skinName, paletteName);
  50. else UserLookAndFeel.Default.SetSkinStyle(skinName);
  51. CultureInfo culture = CultureInfo.CreateSpecificCulture(CultureName);
  52. Application.CurrentCulture = culture;
  53. Thread.CurrentThread.CurrentUICulture = culture;
  54. Thread.CurrentThread.CurrentCulture = culture;
  55. CultureInfo.DefaultThreadCurrentCulture = culture;
  56. CultureInfo.DefaultThreadCurrentUICulture = culture;
  57. UserLookAndFeel.Default.StyleChanged += (sender, e) =>
  58. {
  59. AppConfigHelper.SetAppSetting("SkinName", UserLookAndFeel.Default.ActiveSkinName);
  60. AppConfigHelper.SetAppSetting("PaletteName", UserLookAndFeel.Default.ActiveSvgPaletteName);
  61. };
  62. }
  63. static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
  64. {
  65. string errMsg = "发生未知错误,请联系管理员!" + e.Exception?.Message;
  66. if (e.GetType().ToString().EndsWith("OracleException"))
  67. IocContainer.Logger.Error(e.Exception,"数据库连接异常");
  68. else
  69. IocContainer.Logger.Error(e.Exception,errMsg);
  70. }
  71. static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  72. {
  73. var ex = e.ExceptionObject as Exception;
  74. IocContainer.Logger.Error(ex,"发生未知错误,程序即将退出!");
  75. MsgBoxHelper.ShowError("发生未知错误,程序即将退出!");
  76. }
  77. private static Assembly ResolveAssembly(AssemblyLoadContext alc, AssemblyName assemblyName)
  78. {
  79. string pathMaybe1 = Path.Combine(AppContext.BaseDirectory, $"{assemblyName.Name}.dll");
  80. if (File.Exists(pathMaybe1))
  81. return alc.LoadFromAssemblyPath(pathMaybe1);
  82. string pathMaybe2 = Path.Combine(AppContext.BaseDirectory, "AddIns", $"{assemblyName.Name}.dll");
  83. if (File.Exists(pathMaybe2))
  84. return alc.LoadFromAssemblyPath(pathMaybe2);
  85. return null;
  86. }
  87. public static void OneStart(string appName, Action act)
  88. {
  89. InitAppSettings();
  90. AssemblyLoadContext.Default.Resolving += ResolveAssembly;
  91. //c++dll加入环境变量
  92. string paths = Environment.GetEnvironmentVariable("PATH");
  93. var dirs = Directory.EnumerateDirectories("AddIns", "*", SearchOption.AllDirectories);
  94. List<string> list = new List<string>
  95. {
  96. Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AddIns")
  97. };
  98. foreach (var item in dirs)
  99. {
  100. list.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, item));
  101. }
  102. Environment.SetEnvironmentVariable("PATH", $"{paths};{string.Join(";", list)}");
  103. using (Mutex mutex = new Mutex(true, appName))
  104. {
  105. if (!string.IsNullOrWhiteSpace(appName) && !mutex.WaitOne(0, false))
  106. {
  107. Process currentProcess = Process.GetCurrentProcess();
  108. Process[] processesByName = Process.GetProcessesByName(currentProcess.ProcessName);
  109. bool isShow = false;
  110. for (int i = 0; i < processesByName.Length; i++)
  111. {
  112. Process process = processesByName[i];
  113. if (process.Id != currentProcess.Id && process.MainWindowHandle != IntPtr.Zero)
  114. {
  115. isShow = true;
  116. ToolWinApi.SetForegroundWindow(process.MainWindowHandle);
  117. ToolWinApi.RestoreWindowAsync(process.MainWindowHandle);
  118. break;
  119. }
  120. }
  121. if (!isShow)
  122. {
  123. MsgBoxHelper.ShowWarning("已有相同程序在运行,不能重复启动!");
  124. }
  125. }
  126. else
  127. {
  128. act();
  129. }
  130. }
  131. }
  132. public static void MultStart(Action act)
  133. {
  134. act();
  135. }
  136. }
  137. #pragma warning disable CS0649 // 从未对字段“ToolWinApi.Import.WINDOWPOS.hwnd”赋值,字段将一直保持其默认值
  138. public static class ToolWinApi
  139. {
  140. public class WinProcHook
  141. {
  142. public event Action<byte[]> OnDataReceived;
  143. public event Action<ToolWinApi.WindowPosition> OnWindowPosChanged;
  144. public bool ProcessWmCopyData
  145. {
  146. get;
  147. set;
  148. }
  149. public bool ProcessWmWindowPosChanged
  150. {
  151. get;
  152. set;
  153. }
  154. [SecuritySafeCritical]
  155. public static ToolWinApi.WinProcHook Get(IntPtr hwnd)
  156. {
  157. ToolWinApi.WinProcHook winProcHook;
  158. if (!ToolWinApi.winProcs.TryGetValue(hwnd, out winProcHook))
  159. {
  160. winProcHook = new ToolWinApi.WinProcHook(hwnd);
  161. ToolWinApi.winProcs.Add(hwnd, winProcHook);
  162. }
  163. return winProcHook;
  164. }
  165. private WinProcHook(IntPtr hwnd)
  166. {
  167. HwndSource hwndSource = HwndSource.FromHwnd(hwnd);
  168. hwndSource.AddHook(new HwndSourceHook(this.HookProc));
  169. }
  170. [SecuritySafeCritical]
  171. private IntPtr HookProc(IntPtr handle, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
  172. {
  173. if (this.ProcessWmWindowPosChanged && msg == 71)
  174. {
  175. ToolWinApi.Import.WINDOWPOS wINDOWPOS = (ToolWinApi.Import.WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(ToolWinApi.Import.WINDOWPOS));
  176. ToolWinApi.WindowPosition windowPosition = new ToolWinApi.WindowPosition();
  177. windowPosition.Hwnd = wINDOWPOS.hwnd;
  178. windowPosition.HwndInsertAfter = wINDOWPOS.hwndInsertAfter;
  179. windowPosition.Left = wINDOWPOS.x;
  180. windowPosition.Top = wINDOWPOS.y;
  181. windowPosition.Width = wINDOWPOS.cx;
  182. windowPosition.Height = wINDOWPOS.cy;
  183. windowPosition.Flags = (ToolWinApi.SetWindowPosFlags)wINDOWPOS.flags;
  184. if (this.OnWindowPosChanged != null)
  185. {
  186. this.OnWindowPosChanged(windowPosition);
  187. }
  188. }
  189. if (this.ProcessWmCopyData && msg == 74)
  190. {
  191. ToolWinApi.Import.COPYDATASTRUCT cOPYDATASTRUCT = (ToolWinApi.Import.COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(ToolWinApi.Import.COPYDATASTRUCT));
  192. byte[] array = new byte[1];
  193. int num = cOPYDATASTRUCT.cbData / Marshal.SizeOf(array[0]);
  194. array = new byte[num];
  195. Marshal.Copy(cOPYDATASTRUCT.lpData, array, 0, array.Length);
  196. if (this.OnDataReceived != null)
  197. {
  198. this.OnDataReceived(array);
  199. }
  200. handled = true;
  201. }
  202. return IntPtr.Zero;
  203. }
  204. }
  205. public class WindowPosition
  206. {
  207. public IntPtr Hwnd
  208. {
  209. get;
  210. set;
  211. }
  212. public IntPtr HwndInsertAfter
  213. {
  214. get;
  215. set;
  216. }
  217. public int Left
  218. {
  219. get;
  220. set;
  221. }
  222. public int Top
  223. {
  224. get;
  225. set;
  226. }
  227. public int Width
  228. {
  229. get;
  230. set;
  231. }
  232. public int Height
  233. {
  234. get;
  235. set;
  236. }
  237. public ToolWinApi.SetWindowPosFlags Flags
  238. {
  239. get;
  240. set;
  241. }
  242. }
  243. [Flags]
  244. public enum SetWindowPosFlags
  245. {
  246. NoSize = 1,
  247. NoMove = 2,
  248. NoZOrder = 4,
  249. NoRedraw = 8,
  250. NoActivate = 16,
  251. DrawFrame = 32,
  252. FrameChanged = 32,
  253. ShowWindow = 64,
  254. HideWindow = 128,
  255. NoCopyBits = 256,
  256. NoOwnerZOrder = 512,
  257. NoReposition = 512,
  258. NoSendChanging = 1024,
  259. DeferErase = 8192,
  260. AsyncWindowPos = 16384
  261. }
  262. public enum SpecialFolderType
  263. {
  264. CommonDocuments = 46
  265. }
  266. private static class Import
  267. {
  268. public enum SpecialFolderType
  269. {
  270. AdministrativeTools = 48,
  271. CommonAdministrativeTools = 47,
  272. ApplicationData = 26,
  273. CommonAppData = 35,
  274. CommonDocuments = 46,
  275. Cookies = 33,
  276. CreateFlag = 32768,
  277. History = 34,
  278. InternetCache = 32,
  279. LocalApplicationData = 28,
  280. MyPictures = 39,
  281. Personal = 5,
  282. ProgramFiles = 38,
  283. CommonProgramFiles = 43,
  284. System = 37,
  285. Windows = 36,
  286. Fonts = 20
  287. }
  288. public enum RFlags
  289. {
  290. Any = 65535,
  291. RegNone = 1,
  292. Noexpand = 268435456,
  293. RegBinary = 8,
  294. Dword = 24,
  295. RegDword = 16,
  296. Qword = 72,
  297. RegQword = 64,
  298. RegSz = 2,
  299. RegMultiSz = 32,
  300. RegExpandSz = 4,
  301. RrfZeroonfailure = 536870912
  302. }
  303. public enum RType
  304. {
  305. RegNone,
  306. RegSz,
  307. RegExpandSz,
  308. RegMultiSz = 7,
  309. RegBinary = 3,
  310. RegDword,
  311. RegQword = 11,
  312. RegQwordLittleEndian = 11,
  313. RegDwordLittleEndian = 4,
  314. RegDwordBigEndian,
  315. RegLink,
  316. RegResourceList = 8,
  317. RegFullResourceDescriptor,
  318. RegResourceRequirementsList
  319. }
  320. public enum HookType
  321. {
  322. WH_JOURNALRECORD,
  323. WH_JOURNALPLAYBACK,
  324. WH_KEYBOARD,
  325. WH_GETMESSAGE,
  326. WH_CALLWNDPROC,
  327. WH_CBT,
  328. WH_SYSMSGFILTER,
  329. WH_MOUSE,
  330. WH_HARDWARE,
  331. WH_DEBUG,
  332. WH_SHELL,
  333. WH_FOREGROUNDIDLE,
  334. WH_CALLWNDPROCRET,
  335. WH_KEYBOARD_LL,
  336. WH_MOUSE_LL
  337. }
  338. public struct WINDOWPLACEMENT
  339. {
  340. public int length;
  341. public int flags;
  342. public ToolWinApi.Import.ShowWindowCommands showCmd;
  343. public System.Drawing.Point ptMinPosition;
  344. public System.Drawing.Point ptMaxPosition;
  345. public Rectangle rcNormalPosition;
  346. }
  347. public enum ShowWindowCommands
  348. {
  349. Hide,
  350. Normal,
  351. ShowMinimized,
  352. ShowMaximized,
  353. ShowNoActivate,
  354. Show,
  355. Minimize,
  356. ShowMinNoActive,
  357. ShowNA,
  358. Restore,
  359. ShowDefault,
  360. ForceMinimize
  361. }
  362. public enum GetWindowCmd : uint
  363. {
  364. GW_HWNDFIRST,
  365. GW_HWNDLAST,
  366. GW_HWNDNEXT,
  367. GW_HWNDPREV,
  368. GW_OWNER,
  369. GW_CHILD,
  370. GW_ENABLEDPOPUP
  371. }
  372. public enum SetWindowPosFlags : uint
  373. {
  374. NOSIZE = 1u,
  375. NOMOVE,
  376. NOZORDER = 4u,
  377. NOREDRAW = 8u,
  378. NOACTIVATE = 16u,
  379. DRAWFRAME = 32u,
  380. FRAMECHANGED = 32u,
  381. SHOWWINDOW = 64u,
  382. HIDEWINDOW = 128u,
  383. NOCOPYBITS = 256u,
  384. NOOWNERZORDER = 512u,
  385. NOREPOSITION = 512u,
  386. NOSENDCHANGING = 1024u,
  387. DEFERERASE = 8192u,
  388. ASYNCWINDOWPOS = 16384u
  389. }
  390. public struct WINDOWPOS
  391. {
  392. public IntPtr hwnd;
  393. public IntPtr hwndInsertAfter;
  394. public int x;
  395. public int y;
  396. public int cx;
  397. public int cy;
  398. public int flags;
  399. }
  400. public struct COPYDATASTRUCT
  401. {
  402. public IntPtr dwData;
  403. public int cbData;
  404. public IntPtr lpData;
  405. }
  406. public enum WM : uint
  407. {
  408. WM_COPYDATA = 74u,
  409. WM_WINDOWPOSCHANGED = 71u,
  410. WM_WINDOWPOSCHANGING = 70u
  411. }
  412. public enum GWL
  413. {
  414. GWL_WNDPROC = -4,
  415. GWL_HINSTANCE = -6,
  416. GWL_HWNDPARENT = -8,
  417. GWL_STYLE = -16,
  418. GWL_EXSTYLE = -20,
  419. GWL_USERDATA = -21,
  420. GWL_ID = -12
  421. }
  422. [Flags]
  423. public enum WS : uint
  424. {
  425. WS_OVERLAPPED = 0u,
  426. WS_POPUP = 2147483648u,
  427. WS_CHILD = 1073741824u,
  428. WS_MINIMIZE = 536870912u,
  429. WS_VISIBLE = 268435456u,
  430. WS_DISABLED = 134217728u,
  431. WS_CLIPSIBLINGS = 67108864u,
  432. WS_CLIPCHILDREN = 33554432u,
  433. WS_MAXIMIZE = 16777216u,
  434. WS_BORDER = 8388608u,
  435. WS_DLGFRAME = 4194304u,
  436. WS_VSCROLL = 2097152u,
  437. WS_HSCROLL = 1048576u,
  438. WS_SYSMENU = 524288u,
  439. WS_THICKFRAME = 262144u,
  440. WS_GROUP = 131072u,
  441. WS_TABSTOP = 65536u,
  442. WS_MINIMIZEBOX = 131072u,
  443. WS_MAXIMIZEBOX = 65536u,
  444. WS_CAPTION = 12582912u,
  445. WS_TILED = 0u,
  446. WS_ICONIC = 536870912u,
  447. WS_SIZEBOX = 262144u,
  448. WS_TILEDWINDOW = 13565952u,
  449. WS_OVERLAPPEDWINDOW = 13565952u,
  450. WS_POPUPWINDOW = 2156396544u,
  451. WS_CHILDWINDOW = 1073741824u,
  452. WS_EX_DLGMODALFRAME = 1u,
  453. WS_EX_NOPARENTNOTIFY = 4u,
  454. WS_EX_TOPMOST = 8u,
  455. WS_EX_ACCEPTFILES = 16u,
  456. WS_EX_TRANSPARENT = 32u,
  457. WS_EX_MDICHILD = 64u,
  458. WS_EX_TOOLWINDOW = 128u,
  459. WS_EX_WINDOWEDGE = 256u,
  460. WS_EX_CLIENTEDGE = 512u,
  461. WS_EX_CONTEXTHELP = 1024u,
  462. WS_EX_RIGHT = 4096u,
  463. WS_EX_LEFT = 0u,
  464. WS_EX_RTLREADING = 8192u,
  465. WS_EX_LTRREADING = 0u,
  466. WS_EX_LEFTSCROLLBAR = 16384u,
  467. WS_EX_RIGHTSCROLLBAR = 0u,
  468. WS_EX_CONTROLPARENT = 65536u,
  469. WS_EX_STATICEDGE = 131072u,
  470. WS_EX_APPWINDOW = 262144u,
  471. WS_EX_OVERLAPPEDWINDOW = 768u,
  472. WS_EX_PALETTEWINDOW = 392u,
  473. WS_EX_LAYERED = 524288u,
  474. WS_EX_NOINHERITLAYOUT = 1048576u,
  475. WS_EX_LAYOUTRTL = 4194304u,
  476. WS_EX_COMPOSITED = 33554432u,
  477. WS_EX_NOACTIVATE = 134217728u
  478. }
  479. public const int MAX_PATH = 260;
  480. public const int KEY_QUERY_VALUE = 1;
  481. public const int KEY_SET_VALUE = 2;
  482. public const int KEY_CREATE_SUB_KEY = 4;
  483. public const int KEY_ENUMERATE_SUB_KEYS = 8;
  484. public const int KEY_NOTIFY = 16;
  485. public const int KEY_CREATE_LINK = 32;
  486. public const int KEY_WOW64_32KEY = 512;
  487. public const int KEY_WOW64_64KEY = 256;
  488. public const int KEY_WOW64_RES = 768;
  489. public const int KEY_READ = 131097;
  490. public static UIntPtr HKEY_LOCAL_MACHINE = new UIntPtr(2147483650u);
  491. public static UIntPtr HKEY_CURRENT_USER = new UIntPtr(2147483649u);
  492. public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
  493. public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
  494. public static readonly IntPtr HWND_TOP = new IntPtr(0);
  495. public static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
  496. [DllImport("shell32.dll")]
  497. public static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, [Out] StringBuilder pszPath);
  498. [DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", SetLastError = true)]
  499. public static extern uint RegQueryValueEx(IntPtr hKey, string lpValueName, int lpReserved, ref ToolWinApi.Import.RType lpType, byte[] pvData, ref uint pcbData);
  500. [DllImport("advapi32.dll", SetLastError = true)]
  501. public static extern int RegCloseKey(IntPtr hKey);
  502. [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
  503. public static extern int RegOpenKeyEx(UIntPtr hKey, string subKey, int ulOptions, int samDesired, out IntPtr hkResult);
  504. [DllImport("user32.dll")]
  505. [return: MarshalAs(UnmanagedType.Bool)]
  506. public static extern bool ShowWindow(IntPtr hWnd, ToolWinApi.Import.ShowWindowCommands nCmdShow);
  507. [DllImport("user32.dll", SetLastError = true)]
  508. [return: MarshalAs(UnmanagedType.Bool)]
  509. public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref ToolWinApi.Import.WINDOWPLACEMENT lpwndpl);
  510. [DllImport("user32.dll", SetLastError = true)]
  511. public static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr onlyZero);
  512. [DllImport("user32.dll", SetLastError = true)]
  513. [return: MarshalAs(UnmanagedType.Bool)]
  514. public static extern bool UnhookWindowsHookEx(IntPtr hhk);
  515. [DllImport("user32.dll", SetLastError = true)]
  516. public static extern IntPtr SetWindowsHookEx(ToolWinApi.Import.HookType hookType, IntPtr lpfn, IntPtr hMod, uint dwThreadId);
  517. [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
  518. public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
  519. [DllImport("kernel32.dll", SetLastError = true)]
  520. [return: MarshalAs(UnmanagedType.Bool)]
  521. public static extern bool FreeLibrary(IntPtr hModule);
  522. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  523. public static extern IntPtr LoadLibrary(string lpFileName);
  524. [DllImport("user32.dll")]
  525. [return: MarshalAs(UnmanagedType.Bool)]
  526. public static extern bool GetWindowPlacement(IntPtr hWnd, ref ToolWinApi.Import.WINDOWPLACEMENT lpwndpl);
  527. [DllImport("user32.dll")]
  528. [return: MarshalAs(UnmanagedType.Bool)]
  529. public static extern bool SetForegroundWindow(IntPtr hWnd);
  530. [DllImport("user32.dll")]
  531. public static extern IntPtr SetFocus(IntPtr hWnd);
  532. [DllImport("user32.dll")]
  533. [return: MarshalAs(UnmanagedType.Bool)]
  534. public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, ToolWinApi.Import.SetWindowPosFlags uFlags);
  535. [DllImport("user32.dll", SetLastError = true)]
  536. public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
  537. [DllImport("user32.dll", SetLastError = true)]
  538. public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
  539. [DllImport("user32.dll", SetLastError = true)]
  540. public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
  541. [DllImport("user32.dll", SetLastError = true)]
  542. public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
  543. [DllImport("user32.dll", SetLastError = true)]
  544. public static extern IntPtr GetWindow(IntPtr hWnd, ToolWinApi.Import.GetWindowCmd uCmd);
  545. [DllImport("user32.dll")]
  546. public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
  547. [DllImport("user32.dll")]
  548. public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
  549. }
  550. private static Dictionary<IntPtr, ToolWinApi.WinProcHook> winProcs = new Dictionary<IntPtr, ToolWinApi.WinProcHook>();
  551. public static readonly IntPtr HwndTopmost = ToolWinApi.Import.HWND_TOPMOST;
  552. public static readonly IntPtr HwndNoTopmost = ToolWinApi.Import.HWND_NOTOPMOST;
  553. public static readonly IntPtr HwndTop = ToolWinApi.Import.HWND_TOP;
  554. public static readonly IntPtr HwndBottom = ToolWinApi.Import.HWND_BOTTOM;
  555. [SecuritySafeCritical]
  556. public static IntPtr LoadLibrary(string filePath)
  557. {
  558. return ToolWinApi.Import.LoadLibrary(filePath);
  559. }
  560. [SecuritySafeCritical]
  561. public static void FreeLibrary(IntPtr hmodule)
  562. {
  563. ToolWinApi.Import.FreeLibrary(hmodule);
  564. }
  565. [SecuritySafeCritical]
  566. public static IntPtr GetProcAddress(IntPtr hmodule, string procName)
  567. {
  568. return ToolWinApi.Import.GetProcAddress(hmodule, procName);
  569. }
  570. [SecuritySafeCritical]
  571. public static void MakeWindowChild(IntPtr hwnd)
  572. {
  573. ToolWinApi.Import.WS wS = (ToolWinApi.Import.WS)ToolWinApi.Import.GetWindowLong(hwnd, -16);
  574. wS |= ToolWinApi.Import.WS.WS_CHILD;
  575. wS &= ~ToolWinApi.Import.WS.WS_POPUP;
  576. ToolWinApi.Import.SetWindowLong(hwnd, -16, (int)wS);
  577. }
  578. [SecuritySafeCritical]
  579. public static void SetWindowParent(IntPtr hwnd, IntPtr newParentHwnd)
  580. {
  581. ToolWinApi.Import.SetParent(hwnd, newParentHwnd);
  582. }
  583. [SecuritySafeCritical]
  584. public static void MoveWindow(IntPtr hwnd, int x, int y, int width, int height, bool repaint)
  585. {
  586. ToolWinApi.Import.MoveWindow(hwnd, x, y, width, height, repaint);
  587. }
  588. [SecuritySafeCritical]
  589. public static IntPtr GetPrevWindow(IntPtr hwnd)
  590. {
  591. return ToolWinApi.Import.GetWindow(hwnd, ToolWinApi.Import.GetWindowCmd.GW_HWNDPREV);
  592. }
  593. [SecuritySafeCritical]
  594. public static IntPtr GetNextWindow(IntPtr hwnd)
  595. {
  596. return ToolWinApi.Import.GetWindow(hwnd, ToolWinApi.Import.GetWindowCmd.GW_HWNDNEXT);
  597. }
  598. [SecuritySafeCritical]
  599. public static void SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int width, int height, ToolWinApi.SetWindowPosFlags flags)
  600. {
  601. ToolWinApi.Import.SetWindowPos(hwnd, hwndInsertAfter, x, y, width, height, (ToolWinApi.Import.SetWindowPosFlags)flags);
  602. }
  603. [SecuritySafeCritical]
  604. public static IntPtr SetFocus(IntPtr hwnd)
  605. {
  606. return ToolWinApi.Import.SetFocus(hwnd);
  607. }
  608. [SecuritySafeCritical]
  609. public static bool SetForegroundWindow(IntPtr hwnd)
  610. {
  611. return ToolWinApi.Import.SetForegroundWindow(hwnd);
  612. }
  613. [SecuritySafeCritical]
  614. public static bool RestoreWindowAsync(IntPtr hwnd)
  615. {
  616. return ToolWinApi.Import.ShowWindowAsync(hwnd, 9);
  617. }
  618. [SecuritySafeCritical]
  619. public static void SendData(IntPtr hwnd, byte[] data)
  620. {
  621. int cbData;
  622. IntPtr intPtr = ToolWinApi.IntPtrAlloc(data, out cbData);
  623. IntPtr intPtr2 = ToolWinApi.IntPtrAlloc<ToolWinApi.Import.COPYDATASTRUCT>(new ToolWinApi.Import.COPYDATASTRUCT
  624. {
  625. dwData = (IntPtr)49329,
  626. lpData = intPtr,
  627. cbData = cbData
  628. });
  629. ToolWinApi.Import.SendMessage(hwnd, 74, IntPtr.Zero, intPtr2);
  630. ToolWinApi.IntPtrFree(intPtr2);
  631. intPtr2 = IntPtr.Zero;
  632. ToolWinApi.IntPtrFree(intPtr);
  633. intPtr = IntPtr.Zero;
  634. }
  635. [SecuritySafeCritical]
  636. public static IntPtr IntPtrAlloc<T>(T param)
  637. {
  638. IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(param));
  639. Marshal.StructureToPtr(param, intPtr, false);
  640. return intPtr;
  641. }
  642. [SecuritySafeCritical]
  643. public static IntPtr IntPtrAlloc(byte[] data, out int size)
  644. {
  645. size = Marshal.SizeOf(data[0]) * data.Length;
  646. IntPtr intPtr = Marshal.AllocHGlobal(size);
  647. Marshal.Copy(data, 0, intPtr, data.Length);
  648. return intPtr;
  649. }
  650. [SecuritySafeCritical]
  651. public static void IntPtrFree(IntPtr preAllocated)
  652. {
  653. if (IntPtr.Zero == preAllocated)
  654. {
  655. return;
  656. }
  657. Marshal.FreeHGlobal(preAllocated);
  658. preAllocated = IntPtr.Zero;
  659. }
  660. [SecuritySafeCritical]
  661. public static IntPtr SetWndProcHook(IntPtr hwnd, IntPtr module, IntPtr hookPtr)
  662. {
  663. return ToolWinApi.Import.SetWindowsHookEx(ToolWinApi.Import.HookType.WH_CALLWNDPROC, hookPtr, module, (uint)ToolWinApi.GetWindowThreadProcessId(hwnd));
  664. }
  665. [SecuritySafeCritical]
  666. public static bool UnhookWindowsHookEx(IntPtr hhook)
  667. {
  668. return ToolWinApi.Import.UnhookWindowsHookEx(hhook);
  669. }
  670. [SecuritySafeCritical]
  671. public static int GetWindowThreadProcessId(IntPtr hwnd)
  672. {
  673. return (int)ToolWinApi.Import.GetWindowThreadProcessId(hwnd, IntPtr.Zero);
  674. }
  675. [SecuritySafeCritical]
  676. public static Rectangle? GetWindowNormalPlacement(IntPtr hwnd)
  677. {
  678. ToolWinApi.Import.WINDOWPLACEMENT wINDOWPLACEMENT = default(ToolWinApi.Import.WINDOWPLACEMENT);
  679. wINDOWPLACEMENT.length = Marshal.SizeOf(wINDOWPLACEMENT);
  680. if (!ToolWinApi.Import.GetWindowPlacement(hwnd, ref wINDOWPLACEMENT))
  681. {
  682. return null;
  683. }
  684. return new Rectangle?(wINDOWPLACEMENT.rcNormalPosition);
  685. }
  686. [SecuritySafeCritical]
  687. public static bool CopyWindowPlacement(IntPtr source, IntPtr dest)
  688. {
  689. ToolWinApi.Import.WINDOWPLACEMENT wINDOWPLACEMENT = default(ToolWinApi.Import.WINDOWPLACEMENT);
  690. wINDOWPLACEMENT.length = Marshal.SizeOf(wINDOWPLACEMENT);
  691. return ToolWinApi.Import.GetWindowPlacement(source, ref wINDOWPLACEMENT) && ToolWinApi.Import.SetWindowPlacement(dest, ref wINDOWPLACEMENT);
  692. }
  693. [SecuritySafeCritical]
  694. public static bool SetWindowState(IntPtr hwnd,System.Windows.WindowState state)
  695. {
  696. ToolWinApi.Import.ShowWindowCommands nCmdShow;
  697. switch (state)
  698. {
  699. case System.Windows.WindowState.Minimized:
  700. nCmdShow = ToolWinApi.Import.ShowWindowCommands.ShowMinimized;
  701. break;
  702. case System.Windows.WindowState.Maximized:
  703. nCmdShow = ToolWinApi.Import.ShowWindowCommands.ShowMaximized;
  704. break;
  705. default:
  706. nCmdShow = ToolWinApi.Import.ShowWindowCommands.Normal;
  707. break;
  708. }
  709. return ToolWinApi.Import.ShowWindow(hwnd, nCmdShow);
  710. }
  711. [SecuritySafeCritical]
  712. public static int SetWindowNoMaximize(IntPtr hwnd)
  713. {
  714. ToolWinApi.Import.WS wS = (ToolWinApi.Import.WS)ToolWinApi.Import.GetWindowLong(hwnd, -16);
  715. wS &= ~ToolWinApi.Import.WS.WS_TABSTOP;
  716. return ToolWinApi.Import.SetWindowLong(hwnd, -16, (int)wS);
  717. }
  718. [SecuritySafeCritical]
  719. public static void MakeWindowTransparent(IntPtr hwnd)
  720. {
  721. ToolWinApi.Import.WS wS = (ToolWinApi.Import.WS)ToolWinApi.Import.GetWindowLong(hwnd, -20);
  722. wS |= (ToolWinApi.Import.WS.WS_SYSMENU | ToolWinApi.Import.WS.WS_EX_TRANSPARENT);
  723. ToolWinApi.Import.SetWindowLong(hwnd, -20, (int)wS);
  724. }
  725. [SecuritySafeCritical]
  726. public static string GetFolderPath(ToolWinApi.SpecialFolderType folderType)
  727. {
  728. StringBuilder stringBuilder = new StringBuilder(260);
  729. int num = ToolWinApi.Import.SHGetFolderPath(IntPtr.Zero, (int)folderType, IntPtr.Zero, 0u, stringBuilder);
  730. if (num != 0)
  731. {
  732. throw new Win32Exception(num);
  733. }
  734. return stringBuilder.ToString();
  735. }
  736. }
  737. #pragma warning restore CS0649 // 从未对字段“ToolWinApi.Import.WINDOWPOS.hwnd”赋值,字段将一直保持其默认值