Advertisement
LittleAngel

Find Mouse Pos from Win API

Feb 20th, 2015
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Runtime.InteropServices;
  4. using System;
  5.  
  6. public class TestMouse : MonoBehaviour {
  7.  
  8. [DllImport("user32.dll")]
  9. [return: MarshalAs(UnmanagedType.Bool)]
  10. static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);
  11.  
  12. [DllImport("user32.dll")]
  13. public static extern bool SetCursorPos(int X, int Y);
  14.  
  15. [DllImport("user32.dll")]
  16. public static extern bool GetCursorPos(out Point pos);
  17.  
  18. [DllImport("user32.dll", SetLastError=true)]
  19. static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
  20.  
  21. [DllImport("user32.dll", EntryPoint = "FindWindow")]
  22. public static extern IntPtr FindWindow(System.String className, System.String windowName);
  23.  
  24. [StructLayout(LayoutKind.Sequential)]
  25. public struct Point
  26. {
  27. public int X;
  28. public int Y;
  29.  
  30. public Point(int x, int y)
  31. {
  32. this.X = x;
  33. this.Y = y;
  34. }
  35. }
  36.  
  37. [StructLayout(LayoutKind.Sequential)]
  38. public struct RECT
  39. {
  40. public int Left; // x position of upper-left corner
  41. public int Top; // y position of upper-left corner
  42. public int Right; // x position of lower-right corner
  43. public int Bottom; // y position of lower-right corner
  44. }
  45.  
  46. private Point mousePos;
  47. private RECT windowPos;
  48. private string labelString;
  49.  
  50. private bool isOutOfWindow(Point mousePosition,RECT windowPosition)
  51. {
  52. if (mousePosition.X > windowPosition.Right || mousePosition.X < windowPosition.Left ||
  53. mousePosition.Y > windowPosition.Bottom || mousePosition.Y < windowPosition.Top)
  54. {
  55. return true;
  56. }
  57.  
  58. return false;
  59.  
  60. }
  61.  
  62. void OnGUI()
  63. {
  64. GUI.Label (new Rect(100,50,450,100),"Mouse Position: " + Input.mousePosition.ToString());
  65.  
  66. if(GetWindowRect (FindWindow(null,"Your Product Name"),out windowPos))
  67. {
  68. GetCursorPos (out mousePos);
  69. GUI.Label (new Rect(100,100,300,100),"Mouse Global Position: " + mousePos.X + " "+mousePos.Y);
  70. GUI.Label (new Rect(100,150,450,100),"Window Position : Bottom:" + windowPos.Bottom + " Top:"+windowPos.Top + " Left:"+windowPos.Left+" Right:"+windowPos.Right);
  71.  
  72. labelString = isOutOfWindow(mousePos,windowPos)== true ? "OUT" : "IN";
  73. GUI.Label(new Rect(Screen.width/2,Screen.height/2,200,80),labelString);
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement