Usually dropdown item start position aligned with ComboBox
start position like the image above.
But i need to develop ComboBox
Control which has the lengthy dropdown item gets aligned in middle.I mean Dropdown item left position should still more left positioned than ComboBox
like the image below. Any help would be greatly appreciated.
Here is an extended ComboBox
which have 2 new useful features to let you set the position and size of drop-down:
DropDownAlignment
: You can set it to Left
, then the drop-down will appear in it's normal position and it's left is aligned with left of control. If you set it to Middle
, the middle of drop-down will be aligned with control and if you set it to Right
, the right of drop-down will be aligned with right of control.
AutoWidthDropDown
: If you set it to true
to, then DropdownWidth
will be set to the width of the longest item. If you set it to false
it uses Width
as DropDownWidth
.
Here is appearance of drop-down after setting AutoWidthDropDown
to true
and DropDownAlignment
to Left
, Middle
and Right
:
You can handle WM_CTLCOLORLISTBOX
message, the lparam
is the handle of drop-down and then you can set position of drop-down using SetWindowPos
.
Also you can calculate width of longest item and set as DropDownWidth
if AutoWidthDropDown
is true.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With