我想获得鼠标,键盘事件的空闲时间

时间:2019-05-31 00:22:37

标签: c# winforms keyboard hook mouse

如果在我什么都不做的情况下鼠标和键盘在一定时间内没有引发事件,我想在c#中显示一个名为“注销”的弹出窗口。

我发现我必须使用钩子。所以我尝试了但是,我可以获得鼠标空闲时间的值,但是无法获取键盘空闲时间的值。键盘空闲时间始终为0。

这是我写的代码。

[Hello, this, is, for, today], 
[my, question]

public partial class Form1 : Form
{

    private Timer timer;
    private InputSource lastInput;
    private KeyboardInput keyboard;
    private MouseInput mouse;

    public Form1()
    {
        InitializeComponent();


        keyboard = new KeyboardInput();
        keyboard.KeyBoardKeyPressed += keyboard_KeyBoardKeyPressed;

        mouse = new MouseInput();
        mouse.MouseMoved += mouse_MouseMoved;

        lastInput = new InputSource();

        timer = new Timer();
        timer.Interval = 1000;
        timer.Tick += Timer1_Tick;
        timer.Start();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        if (GetIdleTime() > 10000)
        {
            timer1.Enabled = false;
            MessageBox.Show("test");
            timer1.Enabled = true;
        }
    }
    private string FormatDateTime(DateTime dateTime)
    {
        return dateTime.ToString("HH:mm:ss");
    }

    private void keyboard_KeyBoardKeyPressed(object sender, EventArgs e)
    {
        Console.WriteLine(GetIdleTime());
        if (GetIdleTime() > 10000)
        {
            timer1.Enabled = false;
            MessageBox.Show("test");
            timer1.Enabled = true;
        }

        label_keyboard.Text = FormatDateTime(lastInput.GetLastInputTime());
    }

    private void mouse_MouseMoved(object sender, EventArgs e)
    {
        Console.WriteLine(GetIdleTime());
        if (GetIdleTime() > 10000)
        {
            timer1.Enabled = false;
            MessageBox.Show("mouse test");
            timer1.Enabled = true;
        }
        label_mouse.Text = FormatDateTime(lastInput.GetLastInputTime());
    }

    private void Timer1_Tick(object sender, EventArgs e)
    {
        //label_lastinput.Text = FormatDateTime(lastInput.GetLastInputTime());
        label_present.Text = FormatDateTime(DateTime.Now);
    }


}

如果我想正确获取键盘和鼠标的空闲时间,该怎么办?

0 个答案:

没有答案