C# 設置鼠標光標位置


C# 設置鼠標光標位置

using System.Drawing;
using System.Runtime.InteropServices;

namespace ZB.QueueSys.Common
{
    public class MouseHelper
    {
        private static MouseHelper instance;
        public static MouseHelper Instance
        {
            get
            {
                if (instance == null) instance = new MouseHelper();
                return MouseHelper.instance;
            }
        }

        /// <summary>
        /// 引用user32.dll動態鏈接庫(windows api),
        /// 使用庫中定義 API:SetCursorPos 
        /// </summary>
        [DllImport("user32.dll")]
        private static extern int SetCursorPos(int x, int y);
        /// <summary>
        /// 移動鼠標到指定的坐標點
        /// </summary>
        public void MoveMouseToPoint(Point p)
        {
            SetCursorPos(p.X, p.Y);
        }
        /// <summary>
        /// 設置鼠標的移動范圍
        /// </summary>
        public void SetMouseRectangle(Rectangle rectangle)
        {
            System.Windows.Forms.Cursor.Clip = rectangle;
        }
        /// <summary>
        /// 設置鼠標位於屏幕中心
        /// </summary>
        public void SetMouseAtCenterScreen()
        {
            int winHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
            int winWidth = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
            Point centerP = new Point(winWidth / 2, winHeight / 2);
            MoveMouseToPoint(centerP);
        }

    }
}


調用測試如下:
            int y = Screen.PrimaryScreen.WorkingArea.Height - 180;
            int x = Screen.PrimaryScreen.WorkingArea.Width - 180;
            Point p = new Point(x, y);
            MouseHelper.Instance.MoveMouseToPoint(p);    

C#獲取指定控件所在屏幕的位置

         int x = this.dgvList.Location.X;
            int y = this.dgvList.Location.Y;
            Point p = new Point(x, y);
            Point pp = this.dgvList.PointToScreen(p);
            MouseHelper.Instance.MoveMouseToPoint(pp);

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM