WindowInterops.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Vanara.PInvoke;
  2. using static Vanara.PInvoke.User32;
  3. namespace SinMaiLauncher.Interops
  4. {
  5. public class WindowInterops
  6. {
  7. public static void RemoveBorderVisible(HWND hWnd)
  8. {
  9. var oldVal = (WindowLongFlags)GetWindowLong(hWnd, WindowLongFlags.GWL_STYLE);
  10. if (oldVal != WindowLongFlags.GWL_STYLE)
  11. SetWindowLong(hWnd, WindowLongFlags.GWL_STYLE, (nint)WindowStyles.WS_VISIBLE);
  12. }
  13. public static void SetParent(HWND hWnd, IntPtr hWndContainer)
  14. {
  15. User32.SetParent(hWnd, hWndContainer);
  16. }
  17. public static void FillWindow(HWND hWnd, Control container)
  18. {
  19. var rect = container.ClientRectangle;
  20. // 调整控制台窗口大小,使其填满容器
  21. MoveWindow(hWnd, rect.Left, rect.Top, rect.Width, rect.Height, true);
  22. }
  23. public enum MoveWindowResult
  24. {
  25. Success,
  26. NoChange,
  27. FailGet,
  28. FailSet,
  29. }
  30. public static MoveWindowResult TryMoveWindow(IntPtr hWnd, int x, int y, int w, int h)
  31. {
  32. if (!GetWindowRect(hWnd, out var rc)) return MoveWindowResult.FailGet;
  33. if (x != rc.Left ||
  34. y != rc.Top ||
  35. w != (rc.Right - rc.Left) ||
  36. h != (rc.Bottom - rc.Top))
  37. {
  38. return MoveWindow(hWnd, x, y, w, h, false)
  39. ? MoveWindowResult.Success
  40. : MoveWindowResult.FailSet
  41. ;
  42. }
  43. return MoveWindowResult.NoChange;
  44. }
  45. public static void Maximize(HWND hWnd) => ShowWindow(hWnd, ShowWindowCommand.SW_MAXIMIZE);
  46. public static void Normal(HWND hWnd) => ShowWindow(hWnd, ShowWindowCommand.SW_NORMAL);
  47. }
  48. }