Disabled Item in listBox.

MiPakTeh 1,476 Reputation points
2021-09-16T10:23:21.44+00:00

Hi All,

What want to do is;

disabled certain item in listBox.I want to disabled 2 items here.
listBox1.Items.Add(new ListItem { Name = "LocalMachine" });
listBox1.Items.Add(new ListItem { Name = "============" });

Here some code;

using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Abort_9
{
    public partial class Form1 : Form
    {
        public class ListItem
        {
            public string Name { get; set; }

            public override string ToString()
            {
                return Name;
            }
        }

        const string runKey_ = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
        const string runKey_A = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
        const string runKey_B = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunServices";
        const string runKey_C = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunServicesOnce";
        const string runKey_D = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\Userinit";

        const string runKey1_ = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
        const string runKey_AA = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce";
        const string runKey_BB = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunServices";
        const string runKey_CC = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunServicesOnce";
        const string runKey_DD = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows";


        public Form1()
        {
            InitializeComponent();

            listBox1.Items.Add(new ListItem { Name = "LocalMachine" });
            listBox1.Items.Add(new ListItem { Name = "============" });
            listBox1.Items.Add(new ListItem { Name = runKey_ });
            listBox1.Items.Add(new ListItem { Name = runKey_A });
            listBox1.Items.Add(new ListItem { Name = runKey_B });
            listBox1.Items.Add(new ListItem { Name = runKey_C });
            listBox1.Items.Add(new ListItem { Name = runKey_D });

            listBox1.Items.Add(new ListItem { Name = "" });

            listBox1.Items.Add(new ListItem { Name = "CurrentUser" });
            listBox1.Items.Add(new ListItem { Name = "============" });
            listBox1.Items.Add(new ListItem { Name = runKey1_ });
            listBox1.Items.Add(new ListItem { Name = runKey_AA });
            listBox1.Items.Add(new ListItem { Name = runKey_BB });
            listBox1.Items.Add(new ListItem { Name = runKey_CC });
            listBox1.Items.Add(new ListItem { Name = runKey_DD });




        }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,649 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 83,206 Reputation points
    2021-09-18T08:57:34.84+00:00

    You can just grey items and handle selection
    Something like (to be improved, basic test) =>

    133229-listbox-disable-items.gif

    You fill the items like in your code in a CustomListBox customListBox1, then to disable the 2 first ones :

    customListBox1.AddDisabledItem(0);  
    customListBox1.AddDisabledItem(1);  
    

    Class (add using System.Runtime.InteropServices; at beginning)

    public class CustomListBox : System.Windows.Forms.ListBox  
    {  
        [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
        public static extern short GetKeyState(int nVirtKey);  
      
        [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
        public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);  
      
        public const int LB_SETCURSEL = 0x0186;  
        public const int LBN_SELCHANGE = 1;  
      
        public const int WM_REFLECT = 0x2000;  
        public const int WM_NOTIFY = 0x004E;  
        public const int WM_COMMAND = 0x0111;  
      
        public static int HIWORD(int n)  
        {  
            return (n >> 16) & 0xffff;  
        }  
      
        public static int LOWORD(int n)  
        {  
            return n & 0xffff;  
        }  
      
        protected override void WndProc(ref Message m)  
        {  
            if (m.Msg == WM_REFLECT + WM_COMMAND)  
            {  
                if (HIWORD((int)m.WParam) == LBN_SELCHANGE)  
                {  
                    int nCurrentIndex = this.SelectedIndex;  
                    int nDisabledIndex = lstIndexes.FindIndex(x => x == nCurrentIndex);  
                    if (nDisabledIndex != -1)  
                    {  
                        SendMessage(this.Handle, LB_SETCURSEL, -1, IntPtr.Zero);  
                        bool bDown = (GetKeyState((int)Keys.Down) & 0x8000) == 0x8000;  
                        bool bUp = (GetKeyState((int)Keys.Up) & 0x8000) == 0x8000;  
                        bool bNext = (GetKeyState((int)Keys.Next) & 0x8000) == 0x8000;  
                        bool bPrior = (GetKeyState((int)Keys.Prior) & 0x8000) == 0x8000;  
                        if (bDown || bUp || bNext || bPrior)  
                        {  
                            while (nDisabledIndex != -1 && nCurrentIndex != -1)  
                            {  
                                if (nCurrentIndex != -1)  
                                {  
                                    nDisabledIndex = lstIndexes.FindIndex(x => x == nCurrentIndex);  
                                    if (nDisabledIndex == -1)  
                                    {  
                                        nCurrentIndex = SendMessage(this.Handle, LB_SETCURSEL, nCurrentIndex, IntPtr.Zero);  
                                        break;  
                                    }  
                                    else  
                                    {  
                                        if (bDown)  
                                            nCurrentIndex++;  
                                        else if (bUp)  
                                            nCurrentIndex--;  
                                        else if (bNext)  
                                            nCurrentIndex += 5;  
                                        else if (bPrior)  
                                            nCurrentIndex -= 5;  
                                    }  
                                }  
                            }  
                        }  
                    }  
                }  
            }  
            else  
                base.WndProc(ref m);  
        }  
      
        private List<int> lstIndexes = new List<int>();  
      
        public CustomListBox()  
        {  
            this.DrawMode = DrawMode.OwnerDrawFixed;  
            this.DrawItem += new DrawItemEventHandler(ListBox1_DrawItem);            
        }  
        public void AddDisabledItem(int nItemIndex)  
        {  
            lstIndexes.Add(nItemIndex);  
        }  
      
        private void ListBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)  
        {  
            e.DrawBackground();  
            Brush myBrush = Brushes.Black;  
            int nIndex = lstIndexes.FindIndex(x => x == e.Index);            
            if (nIndex != -1)  
                myBrush = Brushes.LightGray;  
            if (this.Items.Count != 0 )  
                e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);  
            if (nIndex == -1)  
                e.DrawFocusRectangle();  
        }        
    }  
    

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,386 Reputation points
    2021-09-16T11:10:04.073+00:00

    Here you go, uses a custom list box taken from this post and modified a bit along with adding a property to your ListItem to make life easier for disabling. If you don't want the extra property then you need to use another method to get the indices of items to disable, if they are always the same then hard code it

    132722-listboxex.png

    using System;  
    using System.Collections;  
    using System.Collections.Generic;  
    using System.ComponentModel;  
    using System.Drawing;  
    using System.Windows.Forms;  
      
    namespace ListBoxDisableApp  
    {  
        public class ListBoxEx : ListBox  
        {  
            public event EventHandler<IndexEventArgs> DisabledItemSelected;  
            protected virtual void OnDisabledItemSelected(object sender, IndexEventArgs e)  
            {  
                if (DisabledItemSelected != null)  
                {  
                    DisabledItemSelected(sender, e);  
                }  
            }  
            public ListBoxEx()  
            {  
      
                DrawMode = DrawMode.OwnerDrawFixed;  
                disabledIndices = new DisabledIndexCollection(this);  
            }  
      
            private int originalHeight = 0;  
            private bool fontChanged = false;  
      
            protected override void OnFontChanged(EventArgs e)  
            {  
                base.OnFontChanged(e);  
                fontChanged = true;  
                ItemHeight = FontHeight;  
                Height = GetPreferredHeight();  
                fontChanged = false;  
      
            }  
      
            protected override void OnResize(EventArgs e)  
            {  
                base.OnResize(e);  
                if (!fontChanged)  
                    originalHeight = Height;  
            }  
      
            public void DisableItem(int index)  
            {  
                disabledIndices.Add(index);  
            }  
      
            public void EnableItem(int index)  
            {  
                disabledIndices.Remove(index);  
            }  
      
            private int GetPreferredHeight()  
            {  
                if (!IntegralHeight)  
                    return Height;  
      
                int currentHeight = this.originalHeight;  
                int preferredHeight = PreferredHeight;  
                if (currentHeight < preferredHeight)  
                {  
                    // Calculate how many items currentheigh can hold.  
                    int number = currentHeight / ItemHeight;  
      
                    if (number < Items.Count)  
                    {  
                        preferredHeight = number * ItemHeight;  
                        int delta = currentHeight - preferredHeight;  
                        if (ItemHeight / 2 <= delta)  
                        {  
                            preferredHeight += ItemHeight;  
                        }  
      
                        preferredHeight += (SystemInformation.BorderSize.Height * 4) + 3;  
      
                    }  
                    else  
                    {  
                        preferredHeight = currentHeight;  
                    }  
                }  
                else  
                    preferredHeight = currentHeight;  
      
                return preferredHeight;  
      
            }  
      
            protected override void OnSelectedIndexChanged(EventArgs e)  
            {  
                int currentSelectedIndex = SelectedIndex;  
                List<int> selectedDisabledIndices = new List<int>();  
      
                for (int i = 0; i < SelectedIndices.Count; i++)  
                {  
                    if (disabledIndices.Contains(SelectedIndices[i]))  
                    {  
                        selectedDisabledIndices.Add(SelectedIndices[i]);  
                        SelectedIndices.Remove(SelectedIndices[i]);  
                    }  
                }  
                foreach (int index in selectedDisabledIndices)  
                {  
                    IndexEventArgs args = new IndexEventArgs(index);  
                    OnDisabledItemSelected(this, args);  
                }  
      
                if (currentSelectedIndex == SelectedIndex)  
                    base.OnSelectedIndexChanged(e);  
            }  
      
            protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e)  
            {  
                base.OnDrawItem(e);  
      
                if (DesignMode && Items.Count == 0)  
                {  
                    return;  
                }  
      
                if (e.Index != ListBox.NoMatches)  
                {  
                    object item = this.Items[e.Index];  
                    if (disabledIndices.Contains(e.Index))  
                    {  
                        e.Graphics.FillRectangle(SystemBrushes.InactiveBorder, e.Bounds);  
                        if (item != null)  
                        {  
                            e.Graphics.DrawString(item.ToString(), e.Font, SystemBrushes.GrayText, e.Bounds);  
                        }  
                    }  
                    else  
                    {  
                        if (SelectionMode == System.Windows.Forms.SelectionMode.None)  
                        {  
                            e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);  
                            if (item != null)  
                            {  
                                e.Graphics.DrawString(item.ToString(), e.Font, SystemBrushes.WindowText, e.Bounds);  
                            }  
                        }  
                        else  
                        {  
                            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)  
                            {  
                                e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);  
                                e.DrawFocusRectangle();  
                                if (item != null)  
                                {  
                                    e.Graphics.DrawString(item.ToString(), e.Font, SystemBrushes.HighlightText, e.Bounds);  
                                }  
                            }  
                            else  
                            {  
                                e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);  
                                if (item != null)  
                                {  
                                    e.Graphics.DrawString(item.ToString(), e.Font, SystemBrushes.WindowText, e.Bounds);  
                                }  
                            }  
                        }  
                    }  
                }  
            }  
      
            private DisabledIndexCollection disabledIndices;  
      
            public DisabledIndexCollection DisabledIndices => disabledIndices;  
      
            public class DisabledIndexCollection : IList, ICollection, IEnumerable  
            {  
                // Fields  
                private ListBox owner;  
                private List<int> innerList = new List<int>();  
      
      
                // Methods  
                public DisabledIndexCollection(ListBox owner)  
                {  
                    this.owner = owner;  
                }  
      
                public void Add(int index)  
                {  
                    if (((owner != null) && (owner.Items != null)) && ((index != -1) && !Contains(index)))  
                    {  
                        innerList.Add(index);  
                        owner.SetSelected(index, false);  
                    }  
                }  
      
                public void Clear()  
                {  
                    if (owner != null)  
                    {  
                        innerList.Clear();  
                    }  
                }  
      
                public bool Contains(int selectedIndex)  
                {  
                    return (IndexOf(selectedIndex) != -1);  
                }  
      
                public void CopyTo(Array destination, int index)  
                {  
                    int count = Count;  
                    for (int i = 0; i < count; i++)  
                    {  
                        destination.SetValue(this[i], (int)(i + index));  
                    }  
                }  
      
                public IEnumerator GetEnumerator()  
                {  
                    return new SelectedIndexEnumerator(this);  
                }  
      
                public int IndexOf(int selectedIndex)  
                {  
                    if ((selectedIndex >= 0) && (selectedIndex < this.owner.Items.Count))  
                    {  
                        for (int index = 0; index < innerList.Count; index++)  
                        {  
                            if (innerList[index] == selectedIndex)  
                                return index;  
                        }  
                    }  
                    return -1;  
                }  
      
                public void Remove(int index)  
                {  
                    if (((owner != null) && (owner.Items != null)) && ((index != -1) && Contains(index)))  
                    {  
                        innerList.Remove(index);  
                        owner.SetSelected(index, false);  
                    }  
                }  
      
                int IList.Add(object value)  
                {  
                    throw new NotSupportedException("ListBoxSelectedIndexCollectionIsReadOnly");  
                }  
      
                void IList.Clear()  
                {  
                    throw new NotSupportedException("ListBoxSelectedIndexCollectionIsReadOnly");  
                }  
      
                bool IList.Contains(object selectedIndex)  
                {  
                    return ((selectedIndex is int) && Contains((int)selectedIndex));  
                }  
      
                int IList.IndexOf(object selectedIndex)  
                {  
                    if (selectedIndex is int)  
                    {  
                        return IndexOf((int)selectedIndex);  
                    }  
                    return -1;  
                }  
      
                void IList.Insert(int index, object value)  
                {  
                    throw new NotSupportedException("ListBoxSelectedIndexCollectionIsReadOnly");  
                }  
      
                void IList.Remove(object value)  
                {  
                    throw new NotSupportedException("ListBoxSelectedIndexCollectionIsReadOnly");  
                }  
      
                void IList.RemoveAt(int index)  
                {  
                    throw new NotSupportedException("ListBoxSelectedIndexCollectionIsReadOnly");  
                }  
      
                // Properties  
                [Browsable(false)]  
                public int Count => this.innerList.Count;  
      
                public bool IsReadOnly => true;  
      
                public int this[int index] => IndexOf(index);  
      
                bool ICollection.IsSynchronized => true;  
      
                object ICollection.SyncRoot => this;  
      
                bool IList.IsFixedSize => true;  
      
                object IList.this[int index]  
                {  
                    get => this[index];  
                    set => throw new NotSupportedException("ListBoxSelectedIndexCollectionIsReadOnly");  
                }  
      
                // Nested Types  
                private class SelectedIndexEnumerator : IEnumerator  
                {  
                    // Fields  
                    private int current;  
                    private ListBoxEx.DisabledIndexCollection items;  
      
                    // Methods  
                    public SelectedIndexEnumerator(DisabledIndexCollection items)  
                    {  
                        this.items = items;  
                        this.current = -1;  
                    }  
      
                    bool IEnumerator.MoveNext()  
                    {  
                        if (current < (items.Count - 1))  
                        {  
                            this.current++;  
                            return true;  
                        }  
                        this.current = this.items.Count;  
                        return false;  
                    }  
      
                    void IEnumerator.Reset()  
                    {  
                        this.current = -1;  
                    }  
      
                    // Properties  
                    object IEnumerator.Current  
                    {  
                        get  
                        {  
                            if ((this.current == -1) || (this.current == this.items.Count))  
                            {  
                                throw new InvalidOperationException("ListEnumCurrentOutOfRange");  
                            }  
                            return this.items[this.current];  
                        }  
                    }  
                }  
            }  
      
            public new void SetSelected(int index, bool value)  
            {  
                int num = (Items == null) ? 0 : Items.Count;  
                if ((index < 0) || (index >= num))  
                {  
                    throw new ArgumentOutOfRangeException("index");  
                }  
                if (SelectionMode == SelectionMode.None)  
                {  
                    throw new InvalidOperationException("ListBoxInvalidSelectionMode");  
                }  
                if (!disabledIndices.Contains(index))  
                {  
                    if (!value)  
                    {  
                        if (SelectedIndices.Contains(index))  
                            SelectedIndices.Remove(index);  
                    }  
                    else  
                    {  
                        base.SetSelected(index, value);  
                    }  
                }  
                // Selected index deoes not change, however we should redraw the disabled item.  
                else  
                {  
                    if (!value)  
                    {  
                        // Remove selected item if it is in the list of selected indices.  
                        if (SelectedIndices.Contains(index))  
                            SelectedIndices.Remove(index);  
                    }  
      
                }  
                Invalidate(GetItemRectangle(index));  
            }  
        }  
      
        public class IndexEventArgs : EventArgs  
        {  
            private int index;  
            public int Index  
            {  
                get => index;  
      
                set => index = value;  
            }  
            public IndexEventArgs(int index)  
            {  
                Index = index;  
            }  
        }  
    }  
      
      
    

    ListItem

    public class ListItem  
    {  
        public bool Disable { get; set; }  
        public string Name { get; set; }  
        public override string ToString() => Name;  
    }  
    

    Form code

    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
            Shown += OnShown;  
        }  
      
        private void OnShown(object sender, EventArgs e)  
        {  
            listBox1.Items.Add(new ListItem { Name = "LocalMachine" });  
            listBox1.Items.Add(new ListItem { Name = "============", Disable = true});  
            listBox1.Items.Add(new ListItem { Name = "runKey_" });  
            listBox1.Items.Add(new ListItem { Name = "runKey_A" });  
            listBox1.Items.Add(new ListItem { Name = "runKey_B" });  
            listBox1.Items.Add(new ListItem { Name = "runKey_C" });  
            listBox1.Items.Add(new ListItem { Name = "runKey_D" });  
      
            listBox1.Items.Add(new ListItem { Name = "" });  
      
            listBox1.Items.Add(new ListItem { Name = "CurrentUser" });  
            listBox1.Items.Add(new ListItem { Name = "============", Disable = true });  
            listBox1.Items.Add(new ListItem { Name = "runKey1_" });  
            listBox1.Items.Add(new ListItem { Name = "runKey_AA" });  
            listBox1.Items.Add(new ListItem { Name = "runKey_BB" });  
            listBox1.Items.Add(new ListItem { Name = "runKey_CC" });  
            listBox1.Items.Add(new ListItem { Name = "runKey_DD" });  
      
      
            var items = listBox1.Items.OfType<ListItem>()  
                .Select((item, index) => new { Index = index, Item = item })  
                .Where(x => x.Item.Disable)  
                .ToList();  
      
            foreach (var item in items)  
            {  
                listBox1.DisableItem(item.Index);  
            }  
        }  
    }  
    

    EDIT

    Place a button on the form named SelectedButton, add the following code to get the current item if not disabled.

    private void SelectedButton_Click(object sender, EventArgs e)  
    {  
        var current = (ListItem)listBox1.SelectedItem;  
        MessageBox.Show(current != null ? $"{current.Name} {current.Disable}" : $"Disabled item");  
    }