TransparentWindow.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using UnityEngine;
  4. public class TransparentWindow : MonoBehaviour
  5. {
  6. [SerializeField] private Material m_Material;
  7. private struct MARGINS
  8. {
  9. public int cxLeftWidth;
  10. public int cxRightWidth;
  11. public int cyTopHeight;
  12. public int cyBottomHeight;
  13. }
  14. [DllImport("user32.dll")]
  15. private static extern IntPtr GetActiveWindow();
  16. [DllImport("user32.dll")]
  17. private static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);
  18. [DllImport("Dwmapi.dll")]
  19. private static extern uint DwmExtendFrameIntoClientArea(IntPtr hWnd, ref MARGINS margins);
  20. [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
  21. private static extern int SetWindowPos(IntPtr hwnd, IntPtr hwndInsertAfter, int x, int y, int cx, int cy,
  22. int uFlags);
  23. [DllImport("user32.dll")]
  24. static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
  25. [DllImport("user32.dll", EntryPoint = "SetLayeredWindowAttributes")]
  26. static extern int SetLayeredWindowAttributes(IntPtr hwnd, int crKey, byte bAlpha, int dwFlags);
  27. [DllImport("User32.dll")]
  28. private static extern bool SetForegroundWindow(IntPtr hWnd);
  29. const int GWL_STYLE = -16;
  30. const int GWL_EXSTYLE = -20;
  31. const uint WS_POPUP = 0x80000000;
  32. const uint WS_VISIBLE = 0x10000000;
  33. const uint WS_EX_TOPMOST = 0x00000008;
  34. const uint WS_EX_LAYERED = 0x00080000;
  35. const uint WS_EX_TRANSPARENT = 0x00000020;
  36. const int SWP_FRAMECHANGED = 0x0020;
  37. const int SWP_SHOWWINDOW = 0x0040;
  38. const int LWA_ALPHA = 2;
  39. private IntPtr HWND_TOPMOST = new IntPtr(-1);
  40. private IntPtr _hwnd;
  41. void Start()
  42. {
  43. #if !UNITY_EDITOR
  44. MARGINS margins = new MARGINS() { cxLeftWidth = -1 };
  45. _hwnd = GetActiveWindow();
  46. int fWidth = Screen.width;
  47. int fHeight = Screen.height;
  48. SetWindowLong(_hwnd, GWL_STYLE, WS_POPUP | WS_VISIBLE);
  49. SetWindowLong(_hwnd, GWL_EXSTYLE, WS_EX_TOPMOST | WS_EX_LAYERED | WS_EX_TRANSPARENT);//若想鼠标穿透,则将这个注释恢复即可
  50. DwmExtendFrameIntoClientArea(_hwnd, ref margins);
  51. SetWindowPos(_hwnd, HWND_TOPMOST, 0, 0, fWidth, fHeight, SWP_FRAMECHANGED | SWP_SHOWWINDOW);
  52. ShowWindowAsync(_hwnd, 3); //Forces window to show in case of unresponsive app // SW_SHOWMAXIMIZED(3)
  53. #endif
  54. }
  55. void OnRenderImage(RenderTexture from, RenderTexture to)
  56. {
  57. Graphics.Blit(from, to, m_Material);
  58. }
  59. }