在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();}}
}
親測可用!