3

我在 VB6 中有一个 TreeView,它在右键单击节点时使用 PopupMenu。由于 VB6 PopupMenu 默认其位置为鼠标坐标,因此菜单出现在正确的位置。

What I want to accomplish is that the Popupmenu appears at the right place too on a KeyDown event when a TreeView Node is selected. 我怎样才能做到这一点?

4

1 回答 1

2

您需要获取项目的坐标。为此,您需要先获取它的句柄。当你得到矩形时,你必须把它翻译成坐标。

Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByRef lParam As Any) As Long
Private Declare Function MapWindowPoints Lib "user32.dll" (ByVal hwndFrom As Long, ByVal hwndTo As Long, ByRef lppt As Any, ByVal cPoints As Long) As Long

Private Type RECT
  Left As Long
  Top As Long
  Right As Long
  Bottom As Long
End Type

Private Type RECTF
  Left As Single
  Top As Single
  Right As Single
  Bottom As Single
End Type

Private Const TV_FIRST As Long = &H1100&
Private Const TVM_GETITEMRECT As Long = (TV_FIRST + 4)
Private Const TVM_GETNEXTITEM As Long = (TV_FIRST + 10)
Private Const TVGN_CARET As Long = &H9&


Private Function GetSelectedItemRect(ByVal tv As TreeView, ByRef outRect As RECTF) As Boolean
  Dim hItem As Long
  hItem = SendMessage(tv.hwnd, TVM_GETNEXTITEM, TVGN_CARET, ByVal 0&)

  If hItem Then
    Dim r As RECT
    r.Left = hItem

    If SendMessage(tv.hwnd, TVM_GETITEMRECT, 1, r) Then
      MapWindowPoints tv.hwnd, Me.hwnd, r, 2

      outRect.Left = Me.ScaleX(r.Left, vbPixels, Me.ScaleMode)
      outRect.Top = Me.ScaleY(r.Top, vbPixels, Me.ScaleMode)
      outRect.Right = Me.ScaleX(r.Right, vbPixels, Me.ScaleMode)
      outRect.Bottom = Me.ScaleY(r.Bottom, vbPixels, Me.ScaleMode)

      GetSelectedItemRect = True
    End If
  End If

End Function

用法:

Dim r As RECT

If GetSelectedItemRect(TreeView1, r) Then
  PopupMenu whatever, , r.Right, r.Top
End If
于 2011-07-17T21:50:54.473 回答