【问题标题】:How to get mouseposition when context menu appears?出现上下文菜单时如何获取鼠标位置?
【发布时间】:2011-02-08 17:45:34
【问题描述】:

我有一个包含许多图片框的面板。每个图片框都注册了“contextRightMenu”作为它们的上下文菜单。

当上下文菜单弹出时我想要的是获取当前的鼠标位置。

我曾尝试使用 mouseDown 并单击来获取鼠标位置,但这些事件发生在单击上下文菜单的一项后,为时已晚。

上下文菜单的弹出事件不传递鼠标事件参数,所以我不知道如何获取鼠标位置。

如果我能得到鼠标事件参数就很容易了。

那我就可以了:

 this.contextRightClick.Popup += new System.EventHandler(this.contextRightClick_Popup);

// If EventArgs include mouseposition within the sender
private void contextRightClick_Popup)(object sender, EventArgs e)
{
   int iLocationX = sender.Location.X;
   int iLocationY = sender.Location.Y;

   Point pPosition = new Point(iLocationX + e.X, iLocationY + e.Y);  // Location + position within the sender = current mouseposition
}

谁能帮我获取一些鼠标事件参数,或者建议一个在上下文菜单弹出之前运行的事件?

提前致谢

【问题讨论】:

    标签: c# compact-framework event-handling location


    【解决方案1】:

    您希望光标位置相对于被右键单击的 PictureBox 还是相对于父 Panel、父 Window 或可能只是屏幕位置?

    以下内容可能有助于作为起点。在这里,我在整个屏幕上获取当前鼠标坐标,然后使用 contextRightMenu 中的 SourceControl,它是对右键单击的控件实例的引用,我们将屏幕坐标转换为相对于源控件的点。

    void contextRightMenu_Popup(object sender, EventArgs e)
    {
      ContextMenu menu = sender as ContextMenu;
    
      if (menu != null)
      {
        // Get cursor position in screen coordinates
        Point screenPoint = Cursor.Position;
    
        // Convert screen coordinates to a point relative to the control
        // that was right clicked, in your case this would be the relavant 
        // picture box.
        Point pictureBoxPoint = menu.SourceControl.PointToClient(screenPoint);
      }
    }
    

    【讨论】:

    • 嗨!这是我感兴趣的父面板的位置。但我会研究 SourceControl。谢谢
    • 线索是信息是全局可访问的,而不是任何事件参数的一部分。
    【解决方案2】:

    处理 PictureBox 的鼠标点击。像这样的东西(在 vb.net 中):

    Sub OnMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) handles YourPictureBox.mouseclick
    
            If e.Button = Windows.Forms.MouseButtons.Right then
            'if you need the screen posistion
            PointToScreen(New System.Drawing.Point(e.X, e.Y))
            'if you need just the location
            e.Location
    
            end if
    end sub
    

    【讨论】:

    • 找到了一些东西:私有 void panelMouseClick(Object sender, EventArgs e) { MouseEventArgs args = e as MouseEventArgs;但无论如何,args 只是返回 null :(
    • 尝试按原样使用“e”。我认为它是 CF 中的 MouseEventArgs 类型,尽管它是 EventArgs。不过不确定。
    【解决方案3】:

    你可以试试picturebox的MouseClick事件,如果是右键获取位置。

    【讨论】:

    • 鼠标点击没有任何鼠标事件参数
    • 尝试 MouseDown 或 MouseUp 事件。不知道 CF 支持的东西。另请查看 Cursor.Position 属性。
    【解决方案4】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多