Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
838 views
in Technique[技术] by (71.8m points)

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

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)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))
}

But i need someone to fiddle with the four different coordinate systems to make it work.

Related questions

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...