Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
412 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you are using WinForms and will only deploy on Windows machines then it's quite easy to use user32 GetLastInputInfo to handle both mouse and keyboard idling.

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

    if (GetLastInputInfo(ref plii))
      return TimeSpan.FromMilliseconds(Environment.TickCount - plii.dwTime);
    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;
  }
}

And then in your Form

public partial class MyForm : Form
{
  Timer activityTimer = new Timer();
  TimeSpan activityThreshold = TimeSpan.FromMinutes(2);
  bool cursorHidden = false;

  public Form1()
  {
    InitializeComponent();

    activityTimer.Tick += activityWorker_Tick;
    activityTimer.Interval = 100;
    activityTimer.Enabled = true;
  }

  void activityWorker_Tick(object sender, EventArgs e)
  {
    bool shouldHide = User32Interop.GetLastInput() > activityThreshold;
    if (cursorHidden != shouldHide)
    {
      if (shouldHide)
        Cursor.Hide();
      else
        Cursor.Show();

      cursorHidden = shouldHide;
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...