【问题标题】:I have a button with background image. How to trigger a mouseleave event with a certain condition?我有一个带有背景图像的按钮。如何在一定条件下触发 mouseleave 事件?
【发布时间】:2016-05-12 21:38:05
【问题描述】:

我有一个带背景的按钮。我创建了 mouseenter & mouseleave 事件。在 mouseleave 事件中,如果鼠标光标在 2 个坐标之外,则会触发 mouseleave 事件。

private void Button_SpanMouseEnter(object sender, EventArgs e)
    {
        Button x = sender as Button;
        x.Size = new Size(500, 250);
        x.Location = new Point(0, 0);
    }

    private void Button_SpanMouseLeave(object sender, EventArgs e)
    {
        Button x = sender as Button;

        //If cursor is outside of this coordinates(0,0) & (250,125)
        //it will trigger this size
        x.Size = new Size(250,125);
        x.Location = new Point(0, 0);
    }

我的问题是当我离开 500X250 矩形时,它会触发鼠标离开。我希望它在 250X125 矩形中触发。

【问题讨论】:

  • 如果不在预期边界内,您可以处理 MouseLeave 并返回

标签: c# winforms


【解决方案1】:

要归档您正在尝试的效果,您需要使用MouseMove 事件而不是Button_MouseLeave 事件。所以删除你的 Button_SpanMouseLeave 事件并添加这个:

private void button1_MouseMove(object sender, MouseEventArgs e)
{
    Button x = sender as Button;
    Point p = PointToClient(System.Windows.Forms.Control.MousePosition);
    if (p.X > 250|| p.Y >125)
    {
        button1.Size = new Size(250, 125);
        button1.Location = new Point(0, 0);
    }
}

编辑

实际上,您根本不需要 PointToClient 方法。所以代码是这样的:

private void button1_MouseMove(object sender, MouseEventArgs e)
{
    Button x = sender as Button;
    if (e.X > 250|| e.Y >125)
    {
        x.Size = new Size(250, 125);
        x.Location = new Point(0, 0);
    }
}

编辑 2

好的,如果按钮不在0,0,那么最好像这样使用PointToClient

private void button1_MouseMove(object sender, MouseEventArgs e)
{
    Button x = sender as Button;
    Point p = PointToClient(System.Windows.Forms.Control.MousePosition);
    this.label1.Text = p.X.ToString() + " " + p.Y.ToString();
    if (p.X > x.Location.X + 250 || p.Y > x.Location.Y+125)
    {
        button1.Size = new Size(250, 125);
    }
}

【讨论】:

  • 感谢它在我的一种情况下工作,如果坐标是 P(0,0) 到 P(250,125)。如果坐标从 P(100,200) 到 P(350,325) 会怎样
  • 谢谢。但是如果光标在按钮的右侧和底部,则 mousemove 会触发。如果光标在按钮的上方和左侧,它将不会执行。需要明确的是,如果 0≤x≤100 & 0≤y≤200,则不会触发。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2019-12-13
  • 2019-08-08
  • 1970-01-01
  • 2011-11-23
  • 1970-01-01
相关资源
最近更新 更多