首页 > 解决方案 > 将光标隐藏在一定时间内不动并在移动时再次显示

问题描述

我想在一段时间后隐藏光标(如果鼠标没有移动),我想在图片框中移动鼠标时显示光标。我只是无法让它工作......这是我尝试过的:

    // this Never seem to hide the cursor
    private void picBox_MouseMove(object sender, MouseEventArgs e)
    {
        Cursor.Show();
        tim.Stop();
        tim.Start();
    }
    private void tim_Tick(object sender, EventArgs e)
    {
        Cursor.Hide();
        tim.Stop();
    }

-

    // works but in this case I want cursor.ico to be a resource
    private void picBox_MouseMove(object sender, MouseEventArgs e)
    {
        Cursor.Current = Cursors.Default;
        tim.Stop();
        tim.Start();
    }
    private void tim_Tick(object sender, EventArgs e)
    {
        Cursor.Current = new Cursor("cursor.ico");
        tim.Stop();
    }

-

    // Properties.Resources.cursor gives an error even though I added it to my resources
    // cannot convert from 'System.Drawing.Icon' to 'System.IntPtr'
    private void picBox_MouseMove(object sender, MouseEventArgs e)
    {
        Cursor.Current = Cursors.Default;
        tim.Stop();
        tim.Start();
    }
    private void tim_Tick(object sender, EventArgs e)
    {
        Cursor.Current = new Cursor(Properties.Resources.cursor);
        tim.Stop();
    }

标签: c#.netwinforms

解决方案


您需要有一个计时器并处理其Tick事件。在这种情况Tick下,检查鼠标的最后一次移动是否在特定时间之前,然后使用隐藏光标Cursor.Hide()。还有句柄MouseMovePictureBox显示光标的使用Cursor.Show()方法。

注意:不要忘记启用计时器并将计时器设置Interval为一个较短的值,例如300并更改duration以下代码中的值,以获得更短/更长的非活动时间:

DateTime? lastMovement;
bool hidden = false;
int duration = 2;
void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    lastMovement = DateTime.Now;
    if (hidden)
    {
        Cursor.Show();
        hidden = false;
    }
}
private void timer1_Tick(object sender, EventArgs e)
{
    if (!lastMovement.HasValue)
        return;
    TimeSpan elaped = DateTime.Now - lastMovement.Value;
    if (elaped >= TimeSpan.FromSeconds(duration) && !hidden)
    {
        Cursor.Hide();
        hidden = true;
    }
}

推荐阅读