gpt4 book ai didi

c# - 带 list 的组合框

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:29 25 4
gpt4 key购买 nike

如何在 C# 中实现带有 checkList 的组合框?

最佳答案

我自己一直在搞这个。这是一个控件的小示例,其中包含真正的复选框,而不仅仅是绘制它们。这样您就可以真正使用 CheckBox 类必须提供的一切。它用继承 ToolStripDropDownMenu 的自定义下拉菜单替换了 ComboBox 的常规下拉菜单,这允许您向其添加实际控件,并解决了每当您单击某个项目时下拉菜单关闭的问题。您显然希望扩展 MyComboBox 类以满足您的需要,但它应该是一个很好的起点。

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var mcb = new MyComboBox() { Left = 6, Top = 6 };
this.Controls.Add(mcb);

for (int i = 0; i < 20; i++)
{
mcb.AddItem("Item " + i.ToString() );
}
}
}

public class MyComboBox : ComboBox
{
private MyDropDown _dropDown;

public MyComboBox()
{
_dropDown = new MyDropDown() { Width = 200, Height = 200 };
}

public void AddItem(string text)
{
_dropDown.AddControl(new CheckBox() { Text = text });
}

public void ShowDropDown()
{
if (_dropDown != null)
{
_dropDown.Show(this);
}
}

protected override void WndProc(ref Message m)
{
if (m.Msg == WndUI.WM_REFLECT + WndUI.WM_COMMAND)
{
if (WndUI.HIWORD(m.WParam) == WndUI.CBN_DROPDOWN)
{
ShowDropDown();
return;
}
}
base.WndProc(ref m);
}
}

[ToolboxItem(false)]
public class MyDropDown : ToolStripDropDownMenu
{
public MyDropDown()
{
this.ShowImageMargin = this.ShowCheckMargin = false;
this.AutoSize = false;
this.DoubleBuffered = true;
this.Padding = Margin = Padding.Empty;
}

public int AddControl(Control control)
{
var host = new ToolStripControlHost(control);
host.Padding = host.Margin = Padding.Empty;
host.BackColor = Color.Transparent;
return this.Items.Add(host);
}

public void Show(Control control)
{
Rectangle area = control.ClientRectangle;
Point location = control.PointToScreen(new Point(area.Left, area.Top + area.Height));
location = control.PointToClient(location);
Show(control, location, ToolStripDropDownDirection.BelowRight);
this.Focus();
}
}

public static class WndUI
{
public const int
WM_USER = 0x0400,
WM_REFLECT = WM_USER + 0x1C00,
WM_COMMAND = 0x0111,
CBN_DROPDOWN = 7;

public static int HIWORD(IntPtr n)
{
return HIWORD(unchecked((int)(long)n));
}

public static int HIWORD(int n)
{
return (n >> 16) & 0xffff;
}
}

关于c# - 带 list 的组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4918995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com