Right button popup menu

Submitted by Christopher A. Snyder.

The CTreeView class does not handle the right mouse button click in a manner like the Explorer window. Actions like highlighting, setting the active item, and where the right mouse menu pops up require some additional code to obtain the appropriate functionality. This article is intented to illustrate what functions need to be added to your view class for the tree to "act" properly.

(this page was revised to correct several typos and to address the SHIFT-F10 keypress. Revision date 2-20-98)
 

How this works

What need to happen when a user presses the right mouse button is the selected item needs to change, but not the item in focus. In addition the pop-up context sensitive menu should be display at the corner where the mouse clicked. By default, this does not happen. These code additions shift the focus of a tree item based on the where the mouse click occurs. However, when the right mouse button click is completed, (or after the context menu goes away) the selection needs to shift back to the original selected tree item. This is done in the end of the OnContextMenu function through the use of an added member variable.

To handle the SHIFT-F10 key press, this is the keyboard equivalent of a right mouse button click for those who didn't know that (I never use it so I tend to forget it is there), we need to handle the key press command mirrored from the Tree control. The code I have here for this is more a quick fix than a good solution (if someone has a better method send it to me and I will have it updated here). I first look for a shift key press and then set a flag. Then only when the next key pressed is the F10 do I then call the on-context menu function. This is not a real good solution because the use does not have to hold the shift key down to get the menu to pop up. Though it is close and not too big of a deal since few probably even use the SHIFT-F10 sequence anyways.

To add a Right mouse button context sensitive popup menu to a CTreeView which behaves like the Explorer. To do this you need to add command handler functions for the following messages in your CTreeView derived class (CMyTreeView).

WM_RBUTTONDOWN
WM_LBUTTONDOWN
WM_CONTEXTMENU
=TVN_KEYDOWN
There is one more function that I created here to actually create and display you menu from a menu resource and is called

ShowPopupMenu( CPoint& point );
 

You will need to add one member variable to CMyTreeView called m_pOldSel. Enjoy!

class CMyTreeView : public CTreeView
{
...
        // Generated message map functions
protected:
        //{{AFX_MSG(CMyTreeView)
        afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
        afx_msg void OnKeydown(NMHDR* pNMHDR, LRESULT* pResult);
       //}}AFX_MSG
        DECLARE_MESSAGE_MAP()

protected:
        afx_msg void OnContextMenu(CWnd*, CPoint point);
        void CMyTreeView::ShowPopupMenu( CPoint& point );
// member variables
        HTREEITEM m_pOldSel;
};
Place this code in the created functions.
void CMyTreeView::OnLButtonDown(UINT nFlags, CPoint point)
{
        UINT uFlags;
        HTREEITEM htItem = GetTreeCtrl().HitTest(point, &uFlags);
        if ((htItem != NULL) && (uFlags & TVHT_ONITEM))
                GetTreeCtrl().Select(htItem, TVGN_DROPHILITE);
        CTreeView::OnLButtonDown(nFlags, point);
}

void CMyTreeView::OnRButtonDown(UINT nFlags, CPoint point)
{
        UINT uFlags;
        HTREEITEM htItem = GetTreeCtrl().HitTest(point, &uFlags);
        if ((htItem != NULL) && (uFlags & TVHT_ONITEM)) {
                m_pOldSel = GetTreeCtrl().GetSelectedItem();
                GetTreeCtrl().Select(htItem, TVGN_DROPHILITE);
        }
}

void CMyTreeView::OnContextMenu(CWnd* pWnd, CPoint point)
{
        UINT uFlags;
        CTreeCtrl&      treeCtrl = GetTreeCtrl();
        CPoint ptTree = point;
        treeCtrl.ScreenToClient(&ptTree);
        HTREEITEM htItem = treeCtrl.HitTest(ptTree, &uFlags);

        if ((htItem != NULL) && (uFlags & TVHT_ONITEM)) {
                ShowPopupMenu( point );
                treeCtrl.SetItemState(htItem, 0, TVIS_DROPHILITED);
        }
        else
                CTreeView::OnContextMenu(pWnd, point);

        if (m_pOldSel != NULL) {
                treeCtrl.Select(m_pOldSel, TVGN_DROPHILITE);
                m_pOldSel = NULL;
        }
}

void CMyTreeView::ShowPopupMenu( CPoint& point )
{
        if (point.x == -1 && point.y == -1){
                //keystroke invocation
                CRect rect;
                GetClientRect(rect);
                ClientToScreen(rect);

                point = rect.TopLeft();
                point.Offset(5, 5);
        }

        CMenu menu;
        VERIFY(menu.LoadMenu(IDR_POPUP_MY_MENU));

        CMenu* pPopup = menu.GetSubMenu(0);
        ASSERT(pPopup != NULL);
        CWnd* pWndPopupOwner = this;

        while (pWndPopupOwner->GetStyle() & WS_CHILD)
                pWndPopupOwner = pWndPopupOwner->GetParent();

        pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
                pWndPopupOwner);
}

/*       121 vbKeyF10  16 = shift */
// there is probably a more elegant way to handle this, but this method works.
void CMyTreeView::OnKeydown(NMHDR* pNMHDR, LRESULT* pResult) 
{
        TV_KEYDOWN* pTVKeyDown = (TV_KEYDOWN*)pNMHDR;
        static BOOL bShift = FALSE;
        if ( bShift && pTVKeyDown->wVKey == 121 ) {
                HTREEITEM hItem = GetTreeCtrl().GetSelectedItem( );
                CRect rect;
                GetTreeCtrl().GetItemRect( hItem, &rect, TRUE);
                ClientToScreen( rect );
                OnContextMenu( this, CPoint( rect.right, rect.top ) );
        }
        bShift = pTVKeyDown->wVKey == 16;

        *pResult = 0;
}
Chris is a reseach engineer for the Ohio University Avionics Engineering Center.
Feel Free to e-mail him with questions or comments.

Revised on : 3/15/98



Comments

  • Ghd rettetang billig er likt av venninne i sommeren 2013

    Posted by carpinteyrosuz on 06/14/2013 06:56am

    [url=http://www.rettetangnewsnorge.com/]ghd rettetang[/url] Andre varianter eller serie av GHD rettetang inkluderer lilla GHD og GHD Precious Gift Set som kan gjøre en utmerket gave til noen spesiell på valentine, eller som en bursdagsgave. Akkurat på samme måte som du vil handle for andre varer over Internett for å få best mulig avtale, kan du også shoppe rundt på nettet for å få GHD billig hår straighteners.Whether du er en enkeltperson eller salong eier, er denne spesielle hår produktet en utmerket verktøy å ha. Som en saloon eier, kan du gå for GHD IV Salon Styler og andre spesielle serier for salongen. Men at du får intet mindre enn en ekte GHD rettetang. Hvis du blir tilbudt en GHD rettetang til en overraskende lav sats enn du forventer, må du tenke to ganger da dette kan være et rødt flagg for falske produktet. [url=http://www.rettetangnorgenews.net/beste-ghd-rettetang/beste-ghd-rettetang.html]beste ghd rettetang[/url] Billige GHD er alt du skulle trenge å lage perfekte krøller, bevegelse, volum og straight, takket være sin Forhåndbetalingen teknologi og smarte funksjoner. Kjøpe nye GHD flat Strykejern nå! Avrundet kroppen gir større fleksibilitet i stil, og de er i standby-modus – som betyr at hvis du ikke bruker det for en halv time, de bare si “god natt” og vende bort! I tillegg en hel haug med andre avanserte funksjoner, inkludert regn-beskyttelsesmodus i likeretter i kaldt rom, digitale kontroll over temperatur og høy-teknikken keramiske plater, og du vil snart se at noen spenning! [url=http://www.rettetangnorgenews.net/]ghd rettetang[/url] Den offisielle GHD Nettstedet har en liste over alle kjente falske GHD nettsteder. Deres hjemmeside kontrolløren verktøyet lar deg legge inn en nettadresse å sjekke for å se om det selger ekte GHD rettetang. Godkjente GHD nettsteder vil også ha en “GHD godkjent nettforhandler “badge som vises på nettsiden deres, bør du kontrollere at den viser den nyeste dato og klokkeslett samt den riktige nettsiden adressen til å sørge for at godkjente skilt er reell og har faktisk blitt utstedt av GHD.

    Reply
  • Nike Air Max 1 FB publicity, have on the agenda c trick a strong color character, the brand-new shoes

    Posted by Geozyoceada on 04/22/2013 04:10pm

    In the summer in a pane backing bowels the chilling sprite seems to be a godlike creme de la creme, but if the sprite "feet"? Resolution also disclose you a set off, bring a sustenance! This summer, Nike and Sprite [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] and his sneakers to a fuse of classic snow spread of callow, unsullied and downcast color schematic in the undying Nike Air Max 1 shoes romp a like a breath of fresh air cool scent.[url=http://markwarren.org.uk/property-waet.cfm]air max 90[/url] Summer is the duration to choice a clean shoe, shoes should be a acceptable choice. Qualifying series Nike Air Max HomeTurf megalopolis recently at the end of the day comes up, this series in the first-rate Melody Max shoes to London, Paris and Milan the three paid glorification to the iconic metropolis of Europe, combined with the characteristics of the three cities, Sense Max 1 HYP,Allied Max 90 HYP,Air Max 1 and shoes such as Make public Max 95, combined [url=http://northernroofing.co.uk/roofins.cfm]nike free run uk[/url] with the Hyperfuse, as kindly as a collection of materials, such as suede, Whether you crave going or retro-everything.

    Reply
  • WM_CONTEXTMENU

    Posted by RaymondCai on 03/10/2007 01:26pm

    I very appreciate that you shared your idea and code. it helps me a lot. But there is a very funny thing that I can not make right click working for popup menu, I need to double click right botton to popup menu. It seems the only one click did not send message WM_CONTEXTMENU to my program. I know there is some problem of my code, but where? Thanks.

    Reply
  • Something Wrong

    Posted by Legacy on 01/23/2003 12:00am

    Originally posted by: Cagatay Tunali

    This code works only;
    user must left click the menu item before right clicking the menu item. this combination will make the code work.
    but if you select an item in the list, and after that if you right click another item this code does not work correctly. the selected item and the right clicked item is different.

    i discover this when i try to disable the menu item when root is clicked and eanble when a chld is clicked. is there a method to solve this problem. thank you fro your comments and codes.......

    Reply
  • Shift-F10 even easier...

    Posted by Legacy on 01/06/2003 12:00am

    Originally posted by: Greg Williams

    I found that I didn't need to explicitly handle the keypress for Shift-F10 (or the context menu key), the WM_CONTEXTMENU message was automatically generated with (-1, -1) as the point passed.

    Btw, CTreeCtrl::SelectDropTarget(item) is equivalent to CTreeCtrl::Select(item, TVG_DROPHILITE).

    Reply
  • You don't need ShowPopupMenu(...)

    Posted by Legacy on 09/27/2002 12:00am

    Originally posted by: Simon

    .. just put in OnContextMenu(...) code like this:
    
    

    if ((htItem != NULL) && (uFlags & TVHT_ONITEM))
    {
    CMenu menu;
    VERIFY(menu.LoadMenu(IDR_MENU1));
    CMenu* pPopup = menu.GetSubMenu(0);
    ASSERT(pPopup != NULL);
    pPopup->TrackPopupMenu(TPM_RIGHTBUTTON | TPM_CENTERALIGN, point.x, point.y, this, NULL);
    //ShowPopupMenu( point );
    pCtrl->SetItemState(htItem, 0, TVIS_DROPHILITED);
    }
    else ....

    For me this also solved the problems that I had with graying and enabling the menu items.

    Reply
  • The fight against MFC

    Posted by Legacy on 09/09/2002 12:00am

    Originally posted by: Anders Borch

    These days it's almost impossible to get ANY work done without MFC. Microsoft sure did make life difficult for the non-mfc programmer. But I was taught windows programming by Charles Petzold's fine book, so I do my best to stay out of mfc's way. I fought a long battle to get something like this to work without mfc, and finally gave up. I throught that the one sure way to ALWAYS get the right coordinates of the mouse event (even though the tree view does it's best not to give it to me) was through a mouse hook.
    
    

    The NM_RCLICK notifies me that right mouse button was clicked, and I react appropriately. All I need is the right screen coordinates for my popup menu.

    I ended up hooking mouse messages to my thread:

    // global
    HHOOK g_hook ;
    POINT g_point ;

    ...

    // then in my initialization code
    g_hook = SetWindowsHookEx (WH_MOUSE, MouseProc, hInstance, GetCurrentThreadId()) ;

    ...

    // and in my cleanup code
    UnhookWindowsHookEx (g_hook) ;

    ...

    // MouseProc was implemented like this:
    RESULT CALLBACK MouseProc(int code, WPARAM wParam, LPARAM lParam) {
    if (code == HC_ACTION) {
    MOUSEHOOKSTRUCT *mhs = (MOUSEHOOKSTRUCT*)lParam ;
    g_point.x = mhs->pt.x ;
    g_point.y = mhs->pt.y ;
    }
    return CallNextHookEx (g_hook, code, wParam, lParam) ;
    }

    Reply
  • How to implement CTreeCtrl right click Pop up Menu on Dialog?

    Posted by Legacy on 07/18/2002 12:00am

    Originally posted by: eko sulistyo a

    Within CTreeView derived class your method is applicable, but when i'm using CTreeCtrl on My dialog the method is unapplicable. Could you help me with this ?

    Reply
  • TreeCtrl - Right button popup menu:How to enable/disable menu item?

    Posted by Legacy on 05/14/2002 12:00am

    Originally posted by: Mon

    Hi,

    In this sample how will I enable or disable any menu item(Right button popup menu).I tried the function EnableMenuItem() function but its not working.Do i need to do some thing extra??

    Regards,
    Mon

    Reply
  • And another way to do it

    Posted by Legacy on 11/18/2001 12:00am

    Originally posted by: Cla Tischhauser

    How about this solution:
    
    

    - Create a popup "Dummy"

    - access it as follows:

    Private Sub TreeView_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal x As Long, ByVal y As Long)
    'check if right-click AND click on a node
    If Button = 2 And Not TreeView.HitTest(x, y) Is Nothing Then
    'select the node in TreeView
    Set TreeView.SelectedItem = TreeView.HitTest(x, y)
    'show popup
    CommandBars("Dummy").ShowPopup
    End If
    End Sub

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds