我有一个带背景的按钮。我创建了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矩形中触发。
答案 0 :(得分:3)
要实现您正在尝试的效果,而不是Button_MouseLeave
事件,而您需要使用MouseMove
事件。请删除您的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);
}
}