MouseManager.cs 3.0 KB
using System; 
using System.Linq; 
using System.Threading;
using System.Threading.Tasks; 
using TSA_V.Common;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace TSA_V
{
    public  class MouseManager
    {

        public static  void Start()
        {
            Task.Run(() =>
            {
                Run();
            });
        }

        public static void Stop()
        {
            mstart = false;
        }

      static   bool mstart = true;
        public static void Run()
        {
            mstart = true;
            while (mstart)
            {
                try
                {
                    Thread.Sleep(50);
                    if (!Setting_NInit.Set_CursorProcess)
                    {
                    }
                    else
                    {
                        MouseProcess();
                    }
                }
                catch (Exception ex)
                {
                    LogUtil.error("光标处理出错:" + ex.ToString());
                }
            }
            LogUtil.info("光标位置处理线程已退出.");
        }
        private static  Screen GetMainScreen(int index = -1)
        {
            Screen[] sc = Screen.AllScreens;
             
            if (sc.Count() > index)
            {
                if (index < 0 || index >= sc.Length)
                {
                    int i = 0;
                    foreach (Screen s in sc)
                    {
                        if (s.Primary)
                        {
                            return s;
                        }
                    }
                }

            }
            return null;
        }
        [System.Runtime.InteropServices.DllImport("user32.dll")] //导入user32.dll函数库
        public static extern bool GetCursorPos(out System.Drawing.Point lpPoint);//获取鼠标坐标 

        [DllImport("user32.dll")]
        private static extern int SetCursorPos(int x, int y);
        private static void MouseProcess()
        {
            GetCursorPos(out Point mp);
            int mousex = mp.X;  //鼠标当前X坐标
            int mousey = mp.Y;  //鼠标当前Y坐标
            int newX = mousex;
            int newY = mousey;
            Screen mainScreen = GetMainScreen();
            if (mousex < mainScreen.Bounds.Left)
            {
                newX = mainScreen.Bounds.Left;
                SetCursorPos(newX, newY);
            }
            else if (mousex > mainScreen.Bounds.Right)
            {
                newX = mainScreen.Bounds.Right;
                SetCursorPos(newX, newY);
            }
            if (mousey < mainScreen.Bounds.Top)
            {
                newY = mainScreen.Bounds.Top;
                SetCursorPos(newX, newY);
            }
            else if (mousey > mainScreen.Bounds.Bottom)
            {
                newX = mainScreen.Bounds.Bottom;
                SetCursorPos(newX, newY);
            }


        }
    }
}