在一些論壇上看到有人問在unity裡面控制滑鼠的移動範圍,有二種方法,一個是調用windows 系統的 user32.dll的ClipCursor函數
再一種就是 通過Cursor.SetCursor函數
這裡就介紹一下 第一種方法吧,不說廢話了 直接上代碼
[DllImport( "user32.dll", CharSet = CharSet.Auto, ExactSpelling = true )]
[return: MarshalAs( UnmanagedType.Bool )]
public static extern bool ClipCursor( ref RECT rcClip );
[DllImport( "user32.dll" )]
[return: MarshalAs( UnmanagedType.Bool )]
public static extern bool GetClipCursor( out RECT rcClip );
[DllImport( "user32.dll" )]
static extern int GetForegroundWindow( );
[DllImport("user32.dll")]
[return: MarshalAs( UnmanagedType.Bool )]
static extern bool GetWindowRect( int hWnd, ref RECT lpRect );
[StructLayout( LayoutKind.Sequential )]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public RECT( int left, int top, int right, int bottom )
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
}
RECT currentClippingRect;
RECT originalClippingRect = new RECT( );
void Start()
{
hndl = GetForegroundWindow( );
GetWindowRect( hndl, ref currentClippingRect );
GetClipCursor( out originalClippingRect );
ClipCursor( ref currentClippingRect);
}
void OnApplicationQuit()
{
ClipCursor( ref originalClippingRect );
}