【问题标题】:how to call TrackPopupMenu function from managed vb.net code如何从托管 vb.net 代码中调用 TrackPopupMenu 函数
【发布时间】:2013-06-28 05:41:14
【问题描述】:

我正在尝试调用TrackPopupMenu 函数以在运行时从托管的 VB.NET 代码中显示菜单。 以下是我得到的错误:

检测到 PInvokeStackImbalance 消息:对 PInvoke 函数的调用 'UeWIPopupX!UeWIPopupX.mDeclares::TrackPopupMenu' 不平衡 堆栈。这可能是因为托管的 PInvoke 签名确实 与非托管目标签名不匹配。检查调用 PInvoke 签名的约定和参数与目标匹配 非托管签名。

下面是我用于 TrackPopupMenu 函数的声明:

 <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True, CallingConvention:=CallingConvention.StdCall)> _
Friend Function TrackPopupMenu(ByVal hMenu As Long, ByVal wFlags As Integer, ByVal x As Integer, ByVal y As Integer, ByVal nReserved As Integer, ByVal hWnd As IntPtr, ByVal lprc As RECT) As Integer

End Function

下面是调用TrackPopupMenu函数的代码:

 dim lpRc as RECT
 Dim tP As POINTAPI
 Dim lR as Integer  
 Dim lUn as Integer

 lUn = TPM_RIGHTBUTTON Or TPM_TOPALIGN Or TPM_LEFTALIGN Or TPM_RETURNCMD   
  tP.x = 50
  tP.y = 100
 'Here I am getting the error
 lR = TrackPopupMenu(m_ppMenu.Tools(1).hMenu, lUn, tP.x, tP.y, 0, m_hWndOwner, lpRC)

下面是矩形RECT的声明:

<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Structure RECT
    Dim Left As Integer
    Dim Top As Integer
    Dim Right As Integer
    Dim Bottom As Integer
End Structure

TrackPopupMenu 调用过程中的所有参数都有一些值。 我尝试了不同的调用约定,但仍然出现错误。

我无法解决这个问题。有谁知道如何解决这个问题?

【问题讨论】:

    标签: vb.net marshalling unmanaged managed vb6-migration


    【解决方案1】:

    你的声明是错误的。第一个参数是菜单句柄,因此它必须是 IntPtr。最后一个参数是一个指向 RECT 的 指针。 VB.NET 中的 ByRef。由于它实际上并未使用,因此最好将其声明为 ByVal IntPtr,这样就不需要 RECT 声明。在您的通话中传递 IntPtr.Zero。返回值是布尔值,而不是整数。如果返回 False,则抛出 Win32Exception。修复:

    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> _
    Friend Function TrackPopupMenu(ByVal hMenu As IntPtr, ByVal wFlags As Integer, _
        ByVal x As Integer, ByVal y As Integer, ByVal nReserved As Integer, _
        ByVal hWnd As IntPtr, ByVal ignored As IntPtr) As Boolean
    End Function
    

    有一些提示你没有得到正确的菜单,很难想象你是如何想出 Long 作为参数类型的。请注意,这个函数已经巧妙地包装在 .NET 中,必须调用它应该是非常罕见的。 .NET ContextMenu 类已经调用了 TrackPopupMenu。 ContextMenuStrip 类提供了更现代的版本,具有更好的呈现选项。

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多