unity3d 控制鼠标的移动范围

本文介绍了一种在Unity中使用Windows系统API控制鼠标移动范围的方法。通过调用user32.dll中的ClipCursor函数实现对鼠标活动区域的限制,并提供了具体的C#代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一些论坛上看到有人问在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 );

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值