Hide mouse cursor after an idle time

前端 未结 3 1683
南笙
南笙 2020-12-02 19:25

I want to hide my mouse cursor after an idle time and it will be showed up when I move the mouse. I tried to use a timer but it didn\'t work well. Can anybody help me? Pleas

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 20:06

    Here is a contrived example of how to do it. You probably had some missing logic that was overriding the cursor's visibility:

    public partial class Form1 : Form
    {
        public TimeSpan TimeoutToHide { get; private set; }
        public DateTime LastMouseMove { get; private set; }
        public bool IsHidden { get; private set; }
    
        public Form1()
        {
            InitializeComponent();
            TimeoutToHide = TimeSpan.FromSeconds(5);
            this.MouseMove += new MouseEventHandler(Form1_MouseMove);
        }
    
        void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            LastMouseMove = DateTime.Now;
    
            if (IsHidden) 
            { 
                Cursor.Show(); 
                IsHidden = false; 
            }
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
            TimeSpan elaped = DateTime.Now - LastMouseMove;
            if (elaped >= TimeoutToHide && !IsHidden)
            {
                Cursor.Hide();
                IsHidden = true;
            }
        }
    }
    

提交回复
热议问题