DevExpress TreeList添加右键菜单问题

添加右键流程:

1.先在窗体上拖两个控件,分别是popupMenu和barManager

2.barManager中绑定form属性为当前窗体名称

3.点击barManager右键选择customize,可直接添加子菜单,如果需要有工具栏、菜单栏、状态栏、怎选择Designer,可添加,然后在选择customize,添加command命令,再command选中菜单中执行命令

4.绑定右键菜单事件:在MouseDown事件中处理事件

--------------------------------------------------------------------------------------------------

DevExpress  TreeList添加右键菜单时(e.X, e.Y)位置出现问题:

菜单并不是出现在弹出右键的控件上,而是弹出在整个屏幕的右上角。

错误之处就是获得e的位置是以控件为基准的,而show的时候的基准是整个屏幕;有许多控件本身就有绑定右键功能,因此不会出现这个问题。

搜索了下其他人的方法,竟然都不能用,甚为奇怪!

一、最开始的写法:MouseEventArgs e为基准

 private void tlstEquipment_MouseClick(object sender, MouseEventArgs e)
  {if (e.Button == MouseButtons.Right)
       {
         System.Drawing.Point p = new System.Drawing.Point(e.X, e.Y);
         popupMenuTree.ShowPopup(p);
         }   
  }

问题就是菜单显示在右上角。

二、Cursor.Position为基准

主要是参照这里 DevExpress 给TreeList添加右键菜单,注意红色的部分。

        private void treeList1_MouseUp(object sender, MouseEventArgs e)
        {
            TreeList tree = sender as TreeList;
            if (e.Button == MouseButtons.Right 
                    && ModifierKeys == Keys.None
                    && treeList1.State == TreeListState.Regular)
            {
              Point p = new Point(Cursor.Position.X, Cursor.Position.Y);
                TreeListHitInfo hitInfo = tree.CalcHitInfo(e.Location);
                if (hitInfo.HitInfoType == HitInfoType.Cell)
                {
                    tree.SetFocusedNode(hitInfo.Node);
                }

                if (tree.FocusedNode != null)
                {
                    popupMenu1.ShowPopup(p);
                }
            }
        }

然而,并不能使用,实测在Cursor中并无Position这一项,更无法获得x y了。

我是.net framework 3.5,不知道是不是这个的原因。

三、this.Location为基准

参照这里:dev中用popupMenu给TreeList添加右键菜单,用法是e.X+this.Location.X这样。

  if (e.Button == MouseButtons.Right)
       {
         System.Drawing.Point point = new System.Drawing.Point(e.X+this.Location.X + 20, e.Y+this.Location.Y +40); //右键菜单弹出的位置
         popupMenu1.ShowPopup(barManager1, point);
       }

然而,同样不能使用。实测this.Location.X=0。

四、直接使用MousePosition位置

     显示正确。

 private void tlstEquipment_MouseClick(object sender, MouseEventArgs e)
  {if (e.Button == MouseButtons.Right)
       {
           System.Drawing.Point p = new System.Drawing.Point(MousePosition.X, MousePosition.Y);
           popupMenuTree.ShowPopup(p);
        }
       }

奇怪得到是,上面两位给出的代码也应该是平时使用的,不至于是乱写,但为何在我这里无法正常使用呢?

原文地址:https://www.cnblogs.com/GISRSMAN/p/4936294.html