Search code examples
c#winformsmouseeventcursor-position

How to check whether the cursor position is outside of chart control in the windows form?


I am displaying tooltip in the MS chart. When moving from chart control to other controls or form free space , tooltip is not getting hided.

How to check whether the cursor position is outside of chart control in the windows form?

I tried below code, it did not work for me.

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (!chart.ClientRectangle.Contains(chart.PointToClient(new Point(e.X,e.Y))))
    {
        if (ToolTip != null)
            ToolTip.Hide(chart);
     }
 } 

I put trace and checked, If I move to form free space from chart control, the event is firing, only when moving to other control from chart, Form1_MouseMove is not getting called.

How to resolve my problem?


Solution

  • Try handling MouseEnter and MouseLeave events on your target control (the chart in your case, the button in mine).

    using System.Drawing;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp
    {
        public partial class Form1 : Form
        {
            private const string mouseIsOver = "Mouse is over";
            private const string mouseIsOutside = "Mouse is outside";
    
            public Form1()
            {
                InitializeComponent();
                var button = new Button { Text = mouseIsOutside, AutoSize = true, Location = new Point(10, 10) };
                button.MouseEnter += (sender, e) => button.Text = mouseIsOver;
                button.MouseLeave += (sender, e) => button.Text = mouseIsOutside;
                this.Controls.Add(button);
    
            }
        }
    }
    

    enter image description here