1、界面设置
2、代码实现
//判断shift键操作
bool isShiftDown = false;
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey)
{
isShiftDown = false;
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey)
{
isShiftDown = true;
}
}
/// <summary>
/// 根据快捷键选择多个Item
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (isShiftDown && e.NewValue == CheckState.Checked)
{
var items = checkedListBox1.CheckedItems;
var firstCheckItem = items.Count > 0 ? items[0] : null;
if (firstCheckItem != null)
{
//第一次选中的item
int index = checkedListBox1.Items.IndexOf(firstCheckItem);
//最后选择的item
int nowIndex = e.Index;
int i, j;
if (index < nowIndex)
{
i = index;
j = nowIndex;
}
else
{
i = nowIndex;
j = index;
}
checkedListBox1.ItemCheck -= checkedListBox1_ItemCheck;
for (int m = i; m < j; m++)
{
checkedListBox1.SetItemCheckState(m, CheckState.Checked);
}
checkedListBox1.ItemCheck += checkedListBox1_ItemCheck;
}
}
}
/// <summary>
/// 全选
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetItemCheckState(i, CheckState.Checked);
}
}
/// <summary>
/// 取消全选
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);
}
}
/// <summary>
/// 反选
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);
}
else
{
checkedListBox1.SetItemCheckState(i, CheckState.Checked);
}
}
}