Skip to main content Skip to footer

Custom Context Menus for Scrollbars in C1FlexGrid for Winforms

Each one of us must have created context menu for our applications at some point of time. Along with these custom contextmenus, these are some system defined context menus as well. For ex. Context menu appearing inside a Textbox or an editor; or the context menu appearing on scrollbars. Even though these context menus are very helpful, but at times these may not be relevant to your application and you would like to avoid them. So how can we do that? In this blog, we will focus on handling this scenario. Content of this blog is mostly generic and should be applicable to most of the Winforms control. But since we have to use one, we will discuss the code demonstration using C1FlexGrid control. The very first idea that may strike is to cancel the pop up of the context menu. However, the mouse events of C1FlexGrid does not fire when we click on the scrollbar. So the next option we are left with is to inherit the C1FlexGrid control and override the default messaging System. The WndProc method of a control provides access to the Windows message loop for the control. We can trap this event and avoid the display of the default context menu. Once the default menu is suppressed, we can show our own menu. The following code snippet helps you to display your own custom context menu.

public class MyFlexGrid : C1.Win.C1FlexGrid.C1FlexGrid  
{  
    private static readonly int WM_CONTEXTMENU = 123;  
    protected override void WndProc(ref Message m)  
    {  
       if (m.Msg == WM_CONTEXTMENU)  
       {  
          //using Custom Context Menu  
          if (this.HitTest().Row == -1 && this.HitTest().Column == -1)  
          {  
             ContextMenu st = CreateMenu();  
             Point menuLocation = new Point(ScrollBar.MousePosition.X, ScrollBar.MousePosition.Y);  
             st.Show(this, this.PointToClient(menuLocation));  
          }  
          else  
             base.WndProc(ref m);  
          }  
       else  
       {  
          base.WndProc(ref m);  
          this.ContextMenuStrip = null;  
       }  
    }  

    public ContextMenu CreateMenu()  
    {  
       MenuItem[] mi = new MenuItem[3];  
       mi[0] = new MenuItem("Item1", MenuItem_Click);  
       mi[1] = new MenuItem("Item2", MenuItem_Click);  
       mi[2] = new MenuItem("Item3", MenuItem_Click);  
       ContextMenu cm = new ContextMenu(mi);  
       return cm;  
    }  

    void MenuItem_Click(object sender, EventArgs e)  
    {  
       MenuItem mi = sender as MenuItem;  
       if (mi != null)  
       {  
          MessageBox.Show(mi.Text);  
       }  
    }  
}

Download the sample to see the complete implementation. To read more on this WndProc() method, you can refer to the given MSDN Link. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.wndproc.aspx Download Sample

MESCIUS inc.

comments powered by Disqus