.NET:如何检查鼠标是否在控件中?

Ian*_*oyd 3 .net winforms

我想知道鼠标是否在 .NET 中的特定控件中

private void panel1_MouseLeave(object sender, EventArgs e)
{
   if (MouseIsInControl((Control)sender)
      return; //the mouse didn't leave, don't fire a MouseLeave event

   ...
}

public Boolean MouseIsInControl(Control control)
{
    //return (control.Bounds.Contains(MousePosition));
    return control.Bounds.Contains(control.PointToClient(MousePosition))
}
Run Code Online (Sandbox Code Playgroud)

但我需要有人摆弄四个不同的坐标系才能使其工作

相关问题

Vic*_*ard 6

不需要钩子或子类化。

private bool MouseIsOverControl(Button btn) => 
    btn.ClientRectangle.Contains(btn.PointToClient(Cursor.Position))
Run Code Online (Sandbox Code Playgroud)

如果鼠标位于包含控件的窗体之外,则此方法也有效。它使用按钮对象,但您可以使用任何 UI 类

您可以像这样轻松测试该方法:

private void button1_Click(object sender, EventArgs e)
{
    // Sleep to allow you time to move the mouse off the button
    System.Threading.Thread.Sleep(900); 

    // Try moving mouse around or keeping it over the button for different results
    if (MouseIsOverControl(button1))
         MessageBox.Show("Mouse is over the button.");
    else MessageBox.Show("Mouse is NOT over the button.");
}
Run Code Online (Sandbox Code Playgroud)