0

I am having a winform that contains a button which has a context menu strip dropping down when mouse hovers on it.

The condition checking whether the mouse is on the context menu strip is not working in the button's mouse leave event.

private void button1_MouseHover(object sender, EventArgs e)
{           
    contextMenuStrip1.Show(button1, new Point(0, button1.Height));
}

private void button1_MouseLeave(object sender, EventArgs e)
{
    if (contextMenuStrip1.ClientRectangle.Contains(PointToClient(Cursor.Position)))
    {
        return;
    }
    else
    {
        contextMenuStrip1.Hide();
    }
}      
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • The mouse events are not good enough to reliably detect this. A timer can do it, a 100 msec interval is good enough. The Application.Idle event can do it as well. Do note the severe usability problem, it is far too easy for the user to hiccup and bump the mouse out of the menu bounds. As written, that will instantly happen since the mouse is still on the button and won't be on the menu. "Don't do it" is the proper advice. – Hans Passant Nov 05 '18 at 08:57

1 Answers1

0

It's not accurate, but you seem to want this to work.

enter image description here

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp27
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            contextMenuStrip1.MouseLeave += ContextMenuStrip1_MouseLeave;
        }

        private void ContextMenuStrip1_MouseLeave(object sender, EventArgs e)
        {
            contextMenuStrip1.Hide();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            contextMenuStrip1.Show(button1, new Point(0, button1.Height));
        }
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Mr.feel
  • 315
  • 1
  • 3
  • 12
  • I have tried using the contextmenustrip leave event but this is not useful if I move the mouse out of the button without taking the mouse on the contextmenustrip. – Pranoti Bulakh Nov 04 '18 at 03:48