我正在使用Microsoft Blend构建Windows Presentation Foundation控件.
当我通过按下鼠标左键离开我的控件时,不会引发MouseLeave-Event.为什么不?
这是预期的行为:当您mousedown
在控件上执行并离开控件时,控件STILL会在鼠标上保留其"捕获",这意味着控件不会触发控件MouseLeave-Event
.一旦将鼠标按钮释放到控件之外,鼠标离开事件将被触发.
为避免这种情况,您可以简单地告诉控件不要捕获鼠标:
private void ControlMouseDown(System.Object sender, System.Windows.Forms.MouseEventArgs e)
{
Control control = (Control) sender;
control.Capture = false; //release capture.
}
Run Code Online (Sandbox Code Playgroud)
现在,即使在按下按钮时移出,MouseLeave事件也会被触发.
如果您需要Capture INSIDE the Control,您需要付出更多努力:
按下鼠标键时,手动开始跟踪鼠标位置
比较的位置Top
,Left
并Size
在讨论的控件的属性.
决定是否需要停止控制捕获鼠标.
public partial class Form1 : Form
{
private Point point;
private Boolean myCapture = false;
public Form1()
{
InitializeComponent();
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
myCapture = true;
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (myCapture)
{
point = Cursor.Position;
if (!(point.X > button1.Left && point.X < button1.Left + button1.Size.Width && point.Y > button1.Top && point.Y < button1.Top + button1.Size.Height))
{
button1.Capture = false; //this will release the capture and trigger the MouseLeave event immediately.
myCapture = false;
}
}
}
private void button1_MouseLeave(object sender, EventArgs e)
{
MessageBox.Show("Mouse leaving");
}
Run Code Online (Sandbox Code Playgroud)
}
当然你需要myCapture=false;
在MouseUp上停止自己的tracking().忘了一个:)
归档时间: |
|
查看次数: |
4015 次 |
最近记录: |