///
/// MIT License - Copyright(c) 2019 Ugo Belfiore
///
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
using System.Runtime.InteropServices;
using UnityEngine;
namespace MoveMouseEditor
{
public static class Win32Mouse
{
[DllImport("User32.Dll")]
private static extern long SetCursorPos(int x, int y);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(out POINT lpPoint);
private static Vector2 _lastPosition;
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
}
///
/// change the mouse position in window
///
/// wanted position
public static void SetCursorPosition(Vector2 positon)
{
SetCursorPosition((int)positon.x, (int)positon.y);
}
///
/// change the mouse position in window
///
/// wanted position x
/// wanted position y
public static void SetCursorPosition(int x, int y)
{
Win32Mouse.SetCursorPos(x, y);
}
///
/// change the mouse position with the previously saved position.
/// If you did'nt saved the mouse position, set the mouse cursor
/// to 0,0
///
public static void LoadPreviouslySavedPosition()
{
Win32Mouse.SetCursorPosition(Win32Mouse.GetLastSavedPosition());
}
///
/// save the mouse position
///
public static void SavePosition()
{
_lastPosition = GetCursorPosition();
}
///
/// return the last saved position
///
///
public static Vector2 GetLastSavedPosition()
{
return (_lastPosition);
}
///
/// add an offset to the current mouse position
///
/// offset to apply
public static void AddToMousePosition(Vector2 offset)
{
Vector2 currentPosition = Win32Mouse.GetCursorPosition();
Win32Mouse.SetCursorPosition(currentPosition + offset);
}
///
/// return the current mouse position X,Y
///
/// mouse position
public static Vector2 GetCursorPosition()
{
POINT newPoint;
Win32Mouse.GetCursorPos(out newPoint);
return (new Vector2(newPoint.X, newPoint.Y));
}
}
}
#endif