Unable to detect right mouseclick in ComboBox

前端 未结 3 866
清歌不尽
清歌不尽 2021-01-02 23:33

I have a ComboBox that is a simple drop down style. I wanted to open a new window when the user right clicks on an item in the list, but am having trouble getting it to dete

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 00:22

    As an epitaph to this question, you can make this work using normal .NET functionality; you just have to go a little deeper into the event call stack. Instead of handling the MouseClick event, handle the MouseDown event. I had to do something similar recently, and I simply overrode the OnMouseDown method instead of attaching a handler. But, a handler should work too. Here's the code:

        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && !HandlingRightClick)
            {
                HandlingRightClick = true;
                if (!cmsRightClickMenu.Visible)
                    cmsRightClickMenu.Show(this, e.Location);
                else cmsRightClickMenu.Hide();
            }
            base.OnMouseDown(e);
        }
    
        protected override void OnMouseUp(MouseEventArgs e)
        {
            HandlingRightClick = false;
            base.OnMouseUp(e);
        }
    
        private bool HandlingRightClick { get; set; }
    

    The HandlingRightClick property is to prevent multiple triggers of the OnMouseDown logic; the UI will send multiple MouseDown messages, which can interfere with hiding the right-click menu. To prevent this, I only perform the logic once on the first MouseDown trigger (the logic's simple enough that I don't care if two invocations happen to race, but you might), then ignore any other MouseDown triggers until a MouseUp occurs. It's not perfect, but this'll do what you need it to.

提交回复
热议问题