Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

c# - Hide mouse cursor after an idle time

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

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

1 Reply

0 votes
by (71.8m points)

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;
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...