Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide mouse cursor after an idle time

Tags:

c#

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? Please!

like image 566
SuperTux Avatar asked Apr 13 '09 18:04

SuperTux


2 Answers

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;
        }
    }
}
like image 112
Erich Mirabal Avatar answered Sep 21 '22 14:09

Erich Mirabal


Need to account for Environment.Tickcount being negative:

public static class User32Interop
{

    public static TimeSpan GetLastInput()
    {
        var plii = new LASTINPUTINFO();
        plii.cbSize = (uint)Marshal.SizeOf(plii);

        if (GetLastInputInfo(ref plii))
        {
            int idleTime = unchecked(Environment.TickCount - (int)plii.dwTime);
            return TimeSpan.FromMilliseconds(idleTime);
        }
        else
            throw new Win32Exception(Marshal.GetLastWin32Error());
    }

    [DllImport("user32.dll", SetLastError = true)]
    static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

    struct LASTINPUTINFO
    {
        public uint cbSize;
        public uint dwTime;
    }
}
like image 33
mikesl Avatar answered Sep 20 '22 14:09

mikesl