Advertisement
Guest User

Simulate a mouse click in Unity C#

a guest
Sep 13th, 2017
1,078
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Runtime.InteropServices;
  3.  
  4. public class SimulateLeftClick : MonoBehaviour
  5. {
  6. [DllImport("user32.dll")]
  7. public static extern bool SetCursorPos(int X, int Y);
  8.  
  9.  
  10. public void Start()
  11. {
  12. SetCursorPos(50, 50);
  13.  
  14. MouseOperations.MouseEvent(MouseOperations.MouseEventFlags.LeftDown | MouseOperations.MouseEventFlags.LeftUp);
  15. }
  16.  
  17. }
  18.  
  19. public class MouseOperations
  20. {
  21. [System.Flags]
  22. public enum MouseEventFlags
  23. {
  24. LeftDown = 0x00000002,
  25. LeftUp = 0x00000004,
  26. MiddleDown = 0x00000020,
  27. MiddleUp = 0x00000040,
  28. Move = 0x00000001,
  29. Absolute = 0x00008000,
  30. RightDown = 0x00000008,
  31. RightUp = 0x00000010
  32. }
  33.  
  34. [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
  35. [return: MarshalAs(UnmanagedType.Bool)]
  36. private static extern bool SetCursorPos(int X, int Y);
  37.  
  38. [DllImport("user32.dll")]
  39. [return: MarshalAs(UnmanagedType.Bool)]
  40. private static extern bool GetCursorPos(out MousePoint lpMousePoint);
  41.  
  42. [DllImport("user32.dll")]
  43. private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
  44.  
  45. public static void SetCursorPosition(int X, int Y)
  46. {
  47. SetCursorPos(X, Y);
  48. }
  49.  
  50. public static void SetCursorPosition(MousePoint point)
  51. {
  52. SetCursorPos(point.X, point.Y);
  53. }
  54.  
  55. public static MousePoint GetCursorPosition()
  56. {
  57. MousePoint currentMousePoint;
  58. var gotPoint = GetCursorPos(out currentMousePoint);
  59. if (!gotPoint) { currentMousePoint = new MousePoint(0, 0); }
  60. return currentMousePoint;
  61. }
  62.  
  63. public static void MouseEvent(MouseEventFlags value)
  64. {
  65. MousePoint position = GetCursorPosition();
  66.  
  67. mouse_event
  68. ((int)value,
  69. position.X,
  70. position.Y,
  71. 0,
  72. 0)
  73. ;
  74. }
  75.  
  76. [StructLayout(LayoutKind.Sequential)]
  77. public struct MousePoint
  78. {
  79. public int X;
  80. public int Y;
  81.  
  82. public MousePoint(int x, int y)
  83. {
  84. X = x;
  85. Y = y;
  86. }
  87.  
  88. }
  89.  
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement