【问题标题】:C#: How to simulate Mouse Hover event using TimerC#:如何使用 Timer 模拟鼠标悬停事件
【发布时间】:2010-09-29 10:44:17
【问题描述】:

我有一个 fom,它有一个停靠的用户控件来填充。

此用户控件显示不同的图像。每个图像都有 Id,我有一个 imageId 与 imageDetail 对象字典的列表。

此用户控件的鼠标移动事件被捕获,我正在工具提示中显示鼠标的当前 X 和 Y 位置。

当用户将鼠标悬停在图像上一段时间时,我还想在工具提示中显示图像细节。

我尝试使用鼠标悬停事件来执行此操作,但它仅在鼠标进入用户控件绑定时引发。在此之后,如果我在用户控件内移动鼠标鼠标悬停事件不会触发...

如何在工具提示中沿图像细节显示当前 X、Y 位置。

有什么方法可以在鼠标移动中使用一些计时器来模拟鼠标悬停事件。

有没有示例代码..

我解决了这个问题

public partial class Form1 : Form
    {
        Timer timer;
        bool moveStart;
        int count = 0;
        Point prev;

        public Form1()
        {
            InitializeComponent();
            timer = new Timer();
            timer.Interval = 1000;
            timer.Tick += new EventHandler(timer_Tick);
        }

        void timer_Tick(object sender, EventArgs e)
        {
            this.timer.Stop();
            this.moveStart = false;            
            this.toolTip1.SetToolTip(this, string.Format("Mouse Hover"));
            this.textBox1.Text = (++count).ToString();            
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (this.prev.X == e.X && this.prev.Y == e.Y)
                return;
            if (moveStart)
            {
                this.prev = new Point(e.X, e.Y);
                this.timer.Stop();
                this.toolTip1.SetToolTip(this, string.Format("Mouse Move\nX : {0}\nY : {1}", e.X, e.Y));
                this.timer.Start();
            }
            else
            {
                moveStart = true;
            }
        }
    }

【问题讨论】:

标签: c# mouseevent


【解决方案1】:

最简单的方法是从 MouseMove 子例程中调用 MouseOver 子例程,如下所示:

void MouseMove(object sender, MouseEventArgs e)
{
    //Call the MouseHover event
    MouseHover(sender, e);
}

void MouseHover(object sender, EventArgs e)
{
    //MouseHover event code
}

但是,如果您想更好地控制何时以及如何显示工具提示,则需要执行类似于以下的操作:

  1. 在类级别声明一个监听变量。
  2. 挂钩到 MouseHover 事件,以便在鼠标进入时打开监听变量。
  3. 挂钩到 MouseLeave 事件,以便在鼠标离开时关闭监听变量。
  4. 将您的工具提示代码放入 MouseMove 处理程序中,以便在监听变量打开时显示您的工具提示。

这里有一些代码来演示我上面概述的内容。

class Form1
{
    bool showPopup = false;

    void MouseHover(object sender, EventArgs e)
    {
        showPopup = true;
    }

    void MouseLeave(object sender, EventArgs e)
    {
        showPopup = false;
        toolTip.Hide(this);
    }

    void MouseMove(object sender, MouseEventArgs e)
    {
        if (showPopup) 
        {
            toolTip.Show("X: " + e.Location.X + "\r\nY: " + e.Location.Y, 
                         this, e.Location)
        }
    }
}

当然,您必须添加一个名为toolTipToolTip,并将各种方法(子例程)与控件的相应事件(Form、PictureBox 等)相关联。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 2018-10-21
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多