如何使用鼠标悬停移动按钮?

时间:2014-05-07 07:10:09

标签: c# winforms button mousehover

我制作了一个TextBox,用于保留您键入的内容,当您点击相关按钮时,它会为您提供一个消息框。当人们想要点击“否”时,我希望按钮改变位置,这样人们就不能点击它,所以他们被迫点击“是”,问题是鼠标悬停工作只有一次,并且在我离开指针后不会回到初始位置。你能帮助我吗?这是代码:

{
     MsgBox = new CustomMsgBox();
     MsgBox.label1.Text = Text;
     MsgBox.button1.Text = btnOK;
     MsgBox.button2.Text = btnCancel;
     MsgBox.Text = Caption;
     result = DialogResult.No;
     MsgBox.ShowDialog();
     return result;
}

private void button2_Click(object sender, EventArgs e)
{
    button2.Location = new Point(25, 25);
}
private void button2_MouseHover(object sender, EventArgs e)
{

    button2.Location = new Point(+50, +50);
}
private void button2_MouseLeave(object sender, EventArgs e)
{

    button2.Location = new Point(+100, +100);
}

1 个答案:

答案 0 :(得分:1)

您不应该使用MouseLeave,因为当您在MouseHover中移动按钮时,按钮将移动,鼠标将离开按钮区域。这意味着No按钮将从原始位置翻转到新位置并一直返回。您可以做的是使用MouseMove查看用户是否离开Button2最初的区域,然后将其移回。或者包含一个不可见的控件,如button2后面的空标签。然后在标签上设置MouseLeave。

哦,别忘了设置button2.TabStop = false,否则用户可以使用tab来到按钮。

为此做了一个快速而肮脏的概念证明,希望有所帮助;)

public partial class Form1 : Form
{
    private Rectangle buttonRectangle;

    private bool checkRectangle = false;

    public Form1()
    {
        InitializeComponent();
        button2.TabStop = false;
        buttonRectangle = button2.ClientRectangle;
        buttonRectangle.Location = button2.Location;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        button2.Location = new Point(25, 25);
    }

    private void button2_MouseHover(object sender, EventArgs e)
    {
        button2.Location = new Point(50, 50);
        checkRectangle = true;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        if (!checkRectangle)
        {
            return;
        }

        if (!buttonRectangle.Contains(e.X, e.Y))
        {
            checkRectangle = false;
            button2.Location = buttonRectangle.Location;
        }
    }
}

buttonRectangle是根据构建表单时找到按钮的位置设置的。它有一个contains方法,可用于检查是否包含某个点(鼠标移动)。

我还将button2.TabStop设置为false,以便在制表符循环期间不再处于活动状态。

当您的悬停(可以将其更改为鼠标输入,但只是使用您的代码)事件触发时,我将checkRectangle设置为true。我在鼠标移动事件处理程序中使用它来查看是否应该检查任何内容(当鼠标没有“超过”按钮时阻止做任何事情)。

如果buttonRectangle和鼠标位置没有相交,这意味着我们离开了按钮所在的区域,因此我们可以将按钮移回。

相关问题