Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...