What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleDisplay a context menu when the user right-clicks on a ListView control's column headers
DescriptionThis example shows how to display a context menu when the user right-clicks on a ListView control's column headers in Visual Basic 6.
KeywordsListView, context menu, popup menu, right-click, right button, API,
CategoriesControls, API
Subclass the ListView control. In the new WindowProc, look for the WM_PARENTNOTIFY message with the WM_RBUTTONDOWN parameter. When the progtram sees this message, it calls the form's ListViewRightClicked subroutine.
Public Function NewWindowProc(ByVal hwnd As Long, ByVal msg _
    As Long, ByVal wParam As Long, ByVal lParam As Long) As _
Const WM_PARENTNOTIFY As Long = &H210
Const WM_RBUTTONDOWN As Long = &H204

    ' If we're being destroyed,
    ' restore the original WindowProc.
    If msg = WM_NCDESTROY Then
        SetWindowLong _
            hwnd, GWL_WNDPROC, _
    End If

    ' Look for the WM_PARENTNOTIFY message
    ' with the WM_RBUTTONDOWN parameter.
    If (msg = WM_PARENTNOTIFY) And (wParam = _
        WM_RBUTTONDOWN) Then
        ' Tell the form.
        Form1.ListViewRightClicked lParam
    End If

    NewWindowProc = CallWindowProc( _
        OldWindowProc, hwnd, msg, wParam, _
End Function
Subroutine ListViewRightClicked examines the WM_PARENTNOTIFY message's lParam parameter, which holds the mouse's X coordinate in its low word and the mouse's Y coordinate in its high word. The code finds the X corodinate and then loops through the ListView's column widths to see which column contains the mouse. It then sets the mnuPopupItem menu item's caption to display the column number and displays the context menu containing that item. The menu doesn't do anything, it just displays the column number.
' The user has pressed the right mouse button on the
' ListView header.
Public Sub ListViewRightClicked(ByVal lParam As Long)
Dim X As Long
Dim column_num As Integer
Dim i As Integer

    ' Get the X coordinate where the mouse was pressed.
    X = lParam And &HFFFF&

    ' Convert into the form's units.
    X = ScaleX(X, vbPixels, Form1.ScaleMode)

    ' See which column this is.
    column_num = ListView1.ColumnHeaders.Count + 1
    For i = 1 To ListView1.ColumnHeaders.Count
        X = X - ListView1.ColumnHeaders(i).Width
        If X <= 0 Then
            column_num = i
            Exit For
        End If
    Next i

    ' Do something.
    mnuPopupItem.Caption = "Column " & column_num
    PopupMenu mnuPopup
End Sub
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.