代码之家  ›  专栏  ›  技术社区  ›  jasonh

动态生成的下拉菜单出现在屏幕左上角

  •  3
  • jasonh  · 技术社区  · 16 年前

    我在鼠标中插入了一些代码,然后单击工具栏菜单项的事件以在运行时生成菜单,但菜单显示在屏幕的左上角,而不是菜单项下。不管代码是鼠标向下还是点击,菜单总是在错误的地方。我做错什么了?

    以下是代码示例:

    private void windowToolStripMenuItem_MouseDown(object sender, MouseEventArgs e)
    {
        windowToolStripMenuItem.BuildOpenWindowsDropDown(Program.windowManager, (Form f) => (f.SomeProperty == SomeValue));
    }
    

    扩展方法:

    static class ExtensionMethods
    {
        public static void BuildOpenWindowsDropDown(this ToolStripDropDownItem toModify, WindowManager windowManager, Predicate<Form> constraint)
        {
            toModify.DropDownItems.Clear();
            List<Form> windows = windowManager.FindOpenWindows(constraint);
            if (windows != null)
            {
                windows.ForEach((Form f) =>
                {
                    ToolStripItem tsi = toModify.DropDownItems.Add(f.Text);
                    tsi.Tag = f;
                    EventHandler clickHandler = new EventHandler(
                        (object sender, EventArgs e) =>
                        {
                            Form fToShow = (Form)((ToolStripItem)sender).Tag;
                            fToShow.Show();
                        });
                    tsi.Click += clickHandler;
                });
            }
        }
    }
    

    以及WindowManager类中的代码段:

        public List<Form> FindOpenWindows(Predicate<Form> constraint)
        {
            var foundTs = from form in windows
                              where constraint(form)
                                    && form.Created
                              select form;
    
            return foundTs.ToList();
        }
    
    2 回复  |  直到 16 年前
        1
  •  3
  •   Fredrik Mörk    16 年前

    将代码从 MouseDown 事件到 DropDownOpening 事件;这应该给你正确的行为。

        2
  •  0
  •   Adam Robinson    16 年前

    您可能会使用控件本地的坐标(就像鼠标事件中的坐标一样),但使用浮动窗口创建菜单,这需要屏幕坐标。你可以使用 Control.PointToScreen() 函数将控件的本地坐标转换为全局屏幕坐标。只要打电话 PointToScreen() 在引发事件的控件上。