Thursday, March 31, 2011

ListView MouseClick Event

Hi. I have a ListView whereby I want to display one context menu if an item is right-clicked, and another if the click occurs in the ListView control. The problem I'm getting is the MouseClick event is only firing when an item is right-clicked, not the control. What's causing this and how can I get around it?

From stackoverflow
  • Use MouseUp instead of MouseClick! Sorry about that. Should have googled harder.

  • You could subclass the ListView to add a right-click event:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Forms;
    
    namespace MyCustomControls
    {
    
    public delegate void MyDelegate(Object sender, EventArgs e);
    
    class MyListView : ListView
    {
    
        private static readonly object EventRightClickRaised = new object();
    
        public MyListView() 
        {
            //RightClick += new MyDelegate(OnRightClick);
        }
    
        public event EventHandler RightClick
        {
            add
            {
                Events.AddHandler(EventRightClickRaised, value);
            }
            remove
            {
                Events.RemoveHandler(EventRightClickRaised, value);
            }
        }
    
        protected override void OnMouseUp(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                OnRightClick(EventArgs.Empty);
            }
            base.OnMouseUp(e);
        }
    
        protected void OnRightClick(EventArgs e)
        {
            EventHandler RightClickRaised = (EventHandler)Events[EventRightClickRaised];
            if (RightClickRaised != null)
            {
                RightClickRaised(this, e);
            }
        }
    
    }
    }
    
  • I had similar problem (want to catch right clicks on the control), the solution was using MouseEnter(). Should be helpful for what you want to do.

0 comments:

Post a Comment