如何检查鼠标是否在上下文菜单栏上

时间:2018-11-03 20:43:10

标签: c# winforms contextmenustrip

我有一个winform,其中包含一个按钮,当鼠标悬停在该按钮上时,上下文菜单栏会下拉。

检查鼠标是否在上下文菜单栏中的条件在按钮的鼠标离开事件中不起作用。

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

1 个答案:

答案 0 :(得分:0)

这不准确,但是您似乎希望它能起作用。

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