在WinForms的CheckedListBox控件中,默认需要双击才能切换选中状态(复选框勾选)。要实现单击即选中,需要通过代码处理鼠标点击事件并手动切换选中状态。以下是实现步骤:
1.CheckOnClick属性置为true即可。
2.通过事件处理:
2.1.添加CheckedListBox控件:从工具箱拖放控件到窗体。
2.2.处理鼠标点击事件:订阅MouseDown或MouseClick事件。
2.3.获取点击项索引:使用IndexFromPoint()方法。
2.4.切换选中状态:通过SetItemChecked()方法。
private void checkedListBox1_MouseDown(object sender, MouseEventArgs e)
{
// 1. 获取点击位置对应的项索引
int index = checkedListBox1.IndexFromPoint(e.Location);
// 2. 确保点击在有效项上(非空白区域)
if (index >= 0 && index < checkedListBox1.Items.Count)
{
// 3. 切换当前项的选中状态
bool isChecked = checkedListBox1.GetItemChecked(index);
checkedListBox1.SetItemChecked(index, !isChecked);
// 4. [可选] 阻止后续默认选中行为(避免项被高亮)
// 注意:根据需求选择是否添加
if (e.Button == MouseButtons.Left)
{
checkedListBox1.ClearSelected();
}
}
}
亲测可用!