
通常下拉项目开始位置与ComboBox开始位置对齐,就像上面的图像一样。但是我需要开发ComboBox控件,它使冗长的下拉项目在中间对齐,我的意思是下拉项目左边的位置应该比ComboBox更左边,就像下面的图像一样。任何帮助都将不胜感激。

发布于 2016-08-19 14:37:17
下面是一个扩展的ComboBox,它有两个新的有用特性,可以让您设置下拉列表的位置和大小:
DropDownAlignment:您可以将其设置为Left,然后下拉显示在它的正常位置上,它的左边与控制的左边对齐。如果将其设置为Middle,则下拉菜单的中间将与控件对齐,如果将其设置为Right,则下拉权限将与控制权对齐。AutoWidthDropDown:如果您将其设置为true,那么DropdownWidth将被设置为最长项的宽度。如果将其设置为false,则使用Width作为DropDownWidth。下面是将AutoWidthDropDown设置为true、DropDownAlignment设置为Left、Middle和Right后的下拉显示。



实现- ComboBox与DropDown位置和AutoWith DropDown
您可以处理WM_CTLCOLORLISTBOX消息,lparam是下拉的句柄,然后可以使用SetWindowPos设置下拉位置。
此外,如果DropDownWidth为真,则可以计算最长项的宽度,并将其设置为AutoWidthDropDown。
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Linq;public class MyComboBox : ComboBox
{
    private const UInt32 WM_CTLCOLORLISTBOX = 0x0134;
    private const int SWP_NOSIZE = 0x1;
    [DllImport("user32.dll")]
    static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
        int X, int Y, int cx, int cy, uint uFlags);
    public enum DropDownAlignments { Left = 0, Middle, Right }
    public bool AutoWidthDropDown { get; set; }
    public DropDownAlignments DropDownAlignment { get; set; }
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_CTLCOLORLISTBOX)  {
            var bottomLeft = this.PointToScreen(new Point(0, Height));
            var x = bottomLeft.X;
            if (DropDownAlignment == MyComboBox.DropDownAlignments.Middle)
                x -= (DropDownWidth - Width) / 2;
            else if (DropDownAlignment == DropDownAlignments.Right)
                x -= (DropDownWidth - Width);
            var y = bottomLeft.Y;
            SetWindowPos(m.LParam, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE);
        }
        base.WndProc(ref m);
    }
    protected override void OnDropDown(EventArgs e)
    {
        if (AutoWidthDropDown)
            DropDownWidth = Items.Cast<Object>().Select(x => GetItemText(x))
                  .Max(x => TextRenderer.MeasureText(x, Font,
                       Size.Empty, TextFormatFlags.Default).Width);
        else
            DropDownWidth = this.Width;
        base.OnDropDown(e);
    }
}https://stackoverflow.com/questions/39019644
复制相似问题