.NET: How to check if the mouse is in a control?

后端 未结 3 1721
梦毁少年i
梦毁少年i 2020-12-18 14:34

i want to know if the mouse is in a particular control in .NET

private void panel1_MouseLeave(object sender, EventArgs e)
{
   if (MouseIsInControl((Control)         


        
3条回答
  •  太阳男子
    2020-12-18 15:06

    No hooks or subclassing needed.

    private bool MouseIsOverControl(Button btn) => 
        btn.ClientRectangle.Contains(btn.PointToClient(Cursor.Position))
    

    This method also works if the mouse is outside of the form containing the control. It uses a button object but you can use any UI class

    You can test the method easily like so:

    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.");
    }
    

提交回复
热议问题