WPF窗口长时间无人操作鼠标自动隐藏

2020/11/24

一、封装好的监视鼠标移动的类文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Runtime.InteropServices;

namespace EBS.Common {
    public class MouseMonitorHelper {
        private static Point mousePosition;    //鼠标的位置
        public static int CheckCount;   //检测鼠标位置的次数

        //判断鼠标是否移动        
        public static bool HaveUsedTo() {
            Point point = GetMousePoint();
            if (point == mousePosition) return false;
            mousePosition = point; return true;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct MPoint {
            public int X;
            public int Y;
            public MPoint(int x, int y) {
                this.X = x;
                this.Y = y;
            }
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool GetCursorPos(out MPoint mpt);

        // 获取当前屏幕鼠标位置           
        public static Point GetMousePoint() {
            MPoint mpt = new MPoint();
            GetCursorPos(out mpt);
            Point p = new Point(mpt.X, mpt.Y);
            return p;
        }
    }
}

二、程序中调用Timer事件:
private DispatcherTimer Timer_MouseMove;

private void Window_Loaded(object sender, RoutedEventArgs e) {
            // 设置鼠标隐藏、显示
            this.Timer_MouseMove = new DispatcherTimer();
            this.Timer_MouseMove.Tick +=new EventHandler(Timer_MouseMove_Tick);
            this.Timer_MouseMove.Interval = new TimeSpan(0, 0, 1);
            this.Timer_MouseMove.Start();
        }


private void Timer_MouseMove_Tick(object sender, EventArgs e) {
            try {
                if (!MouseMonitorHelper.HaveUsedTo()) {
                    MouseMonitorHelper.CheckCount++;
                    if (MouseMonitorHelper.CheckCount == 3) {
                        MouseMonitorHelper.CheckCount = 0;
                        // 关闭按钮隐藏、鼠标隐藏
                        this.cnsExist.Visibility = Visibility.Hidden;
                        Mouse.OverrideCursor = Cursors.None;
                    }
                } else MouseMonitorHelper.CheckCount = 0;
            } catch {
                throw new NotImplementedException();
            }
        }


private void DockPanel_MouseMove(object sender, MouseEventArgs e) {
            this.cnsExist.Visibility = Visibility.Visible;
            Mouse.OverrideCursor = Cursors.Arrow;