CheckedListBox Control - Only checking the checkbox when the actual checkbox is clicked

前端 未结 6 709
故里飘歌
故里飘歌 2021-01-02 01:14

I\'m using a CheckedListBox control in a small application I\'m working on. It\'s a nice control, but one thing bothers me; I can\'t set a property so that it only checks th

6条回答
  •  有刺的猬
    2021-01-02 01:29

    Well, it is quite ugly, but you could calculate mouse hit coordinates against rectangles of items by hooking on CheckedListBox.MouseDown and CheckedListBox.ItemCheck like the following

    /// 
    /// In order to control itemcheck changes (blinds double clicking, among other things)
    /// 
    bool AuthorizeCheck { get; set; }
    
    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if(!AuthorizeCheck)
            e.NewValue = e.CurrentValue; //check state change was not through authorized actions
    }
    
    private void checkedListBox1_MouseDown(object sender, MouseEventArgs e)
    {
        Point loc = this.checkedListBox1.PointToClient(Cursor.Position);
        for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
        {
            Rectangle rec = this.checkedListBox1.GetItemRectangle(i);
            rec.Width = 16; //checkbox itself has a default width of about 16 pixels
    
            if (rec.Contains(loc))
            {
                AuthorizeCheck = true;
                bool newValue = !this.checkedListBox1.GetItemChecked(i);
                this.checkedListBox1.SetItemChecked(i, newValue);//check 
                AuthorizeCheck = false;
    
                return;
            }
        }
    }
    

提交回复
热议问题