WindowActive.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Runtime.InteropServices;
  4. using System;
  5. using System.Xml;
  6. public class WindowActive : MonoBehaviour
  7. {
  8. [DllImport("User32.dll", EntryPoint = "FindWindow")]
  9. extern static IntPtr FindWindow(string lpClassName, string lpWindowName);
  10. [DllImport("User32.dll")]
  11. extern static bool SetForegroundWindow(IntPtr hWnd);
  12. [DllImport("User32.dll")]
  13. extern static bool ShowWindow(IntPtr hWnd, short State);
  14. public float Wait = 0;//延迟执行
  15. public float Rate = 1;//更新频率
  16. public bool KeepForeground = true;//保持最前
  17. public int Screen_width;
  18. public int Screen_height;
  19. IntPtr hWnd;
  20. bool isCursor;
  21. [DllImport("user32.dll ")]
  22. public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
  23. static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
  24. static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
  25. static readonly IntPtr HWND_TOP = new IntPtr(0);
  26. static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
  27. const UInt32 SWP_NOSIZE = 0x0001;
  28. const UInt32 SWP_NOMOVE = 0x0002;
  29. const UInt32 SWP_NOZORDER = 0x0004;
  30. const UInt32 SWP_NOREDRAW = 0x0008;
  31. const UInt32 SWP_NOACTIVATE = 0x0010;
  32. const UInt32 SWP_FRAMECHANGED = 0x0020;
  33. const UInt32 SWP_SHOWWINDOW = 0x0040;
  34. const UInt32 SWP_HIDEWINDOW = 0x0080;
  35. const UInt32 SWP_NOCOPYBITS = 0x0100;
  36. const UInt32 SWP_NOOWNERZORDER = 0x0200;
  37. const UInt32 SWP_NOSENDCHANGING = 0x0400;
  38. const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
  39. void Start()
  40. {
  41. string path = Application.streamingAssetsPath + "/Setting.xml";
  42. XmlDocument xml = new XmlDocument();
  43. xml.Load(path);
  44. isCursor= bool.Parse( xml.GetElementsByTagName("isCursor")[0].InnerText);
  45. hWnd = HandleManager.GetProcessWnd();
  46. InvokeRepeating("Active", Wait, Rate);
  47. }
  48. /// <summary>
  49. /// 激活窗口
  50. /// </summary>
  51. void Active()
  52. {
  53. if (KeepForeground)
  54. {
  55. try
  56. {
  57. Cursor.visible = isCursor;
  58. ShowWindow(hWnd, 1);
  59. SetForegroundWindow(hWnd);
  60. SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
  61. }
  62. catch { }
  63. }
  64. }
  65. }