c# - 将光标隐藏在一定时间内不动并在移动时再次显示
问题描述
我想在一段时间后隐藏光标(如果鼠标没有移动),我想在图片框中移动鼠标时显示光标。我只是无法让它工作......这是我尝试过的:
// 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();
}
解决方案
您需要有一个计时器并处理其Tick
事件。在这种情况Tick
下,检查鼠标的最后一次移动是否在特定时间之前,然后使用隐藏光标Cursor.Hide()
。还有句柄MouseMove
和PictureBox
显示光标的使用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;
}
}
推荐阅读
- jetbrains-ide - GoLand 在“使用 sudo 运行”配置中保存密码
- hadoop - 在 Kubernetes 上使用 Hadoop
- reactjs - 在显示可能出现也可能不出现的数据时,我在引导网格中遇到问题
- c - 如何在发送数据包时避免填充
- python - 如何为特定索引的数据帧分配具有相同索引的数据帧值
- python - 如何在python中使用for循环创建几个熊猫框架?
- json - 如何在powershell中递归获取所有孩子
- java - 如何在java中有效地计算这个计算?
- bash - 多个读取语句。在给出用户输入之前不要继续
- angularjs - 是否可以使用 ng-file-upload 读取图像的地理位置?