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

如何强制只有当用户单击下拉按钮时才能打开DropDownList样式的组合框?

  •  5
  • Eric  · 技术社区  · 15 年前

    在C#.NET2.0中,我有一个带有ComboBoxStyle下拉列表的WinForms组合框。但是,每当用户单击组合框上的任何位置时,都会出现下拉列表。相反,我希望只有当用户明确单击下拉按钮时它才会打开。当用户单击组合框的其余部分时,我只想将其指定为键盘焦点,这样他或她就可以对所选项目使用一些键盘命令。最好的方法是什么?

    3 回复  |  直到 15 年前
        1
  •  4
  •   Eric    15 年前

    在其他答案的帮助下,我得出了以下快速解决方案:

    public class MyComboBox : ComboBox
    {
        public MyComboBox()
        {
            FlatStyle = FlatStyle.Popup;
            DropDownStyle = ComboBoxStyle.DropDownList;
        }
    
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x0201 /* WM_LBUTTONDOWN */ || m.Msg == 0x0203 /* WM_LBUTTONDBLCLK */)
            {
                int x = m.LParam.ToInt32() & 0xFFFF;
                if (x >= Width - SystemInformation.VerticalScrollBarWidth)
                    base.WndProc(ref m);
                else
                {
                    Focus();
                    Invalidate();
                }
            }
            else
                base.WndProc(ref m);
        }
    }
    
        2
  •  1
  •   John Fisher    15 年前

        void comboBox1_MouseClick(object sender, MouseEventArgs e)
        {
            ComboBox combo = sender as ComboBox;
            int left = combo.Width - (SystemInformation.HorizontalScrollBarThumbWidth + SystemInformation.HorizontalResizeBorderThickness);
            if (e.X >= left)
            {
                // They did click the button, so let it happen.
            }
            else
            {
                // They didn't click the button, so prevent the dropdown.
            }
        }
    

    comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
    

    但是,这允许在框中键入您可能不需要的内容。

    public class CustomComboBox : ComboBox
    {
        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);
    
            int left = this.Width - (SystemInformation.HorizontalScrollBarThumbWidth + SystemInformation.HorizontalResizeBorderThickness);
            if (e.X >= left)
            {
                // They did click the button, so let it happen.
                base.OnMouseClick(e);
            }
            else
            {
                // They didn't click the button, so prevent the dropdown.
                // Just do nothing.
            }
        }
    }
    
        3
  •  0
  •   CodeMonkey1313    15 年前

    你可以得到鼠标点击的X,Y位置,如果它不在下拉“图标”上(因为没有更好的词),你可以从那里强制它折叠。