How to supress user actions on a ListBox control

Viewed 78

Suppose we have a control (e.g. ListBox) and need to lock it from mouse clicks and keyboard actions. Of course, there is a standard property Enabled, but it causes appearance change, undesirable in my case.

I have found a simple solution using Windows API, see below. Suprisingly I haven't found a similar question exactly for my task so let me share this obvious solution with the community.

Any additions and comments are appreciated. In case someone will propose more appropriate/shorter/nicer answer.

1 Answers

We can use Windows API to lock our control from user actions.

First we should find out what standard WinAPI messages will be supressed while posting to the control. In my particular case of ListBox control I have chosen WM_LBUTTONDOWN, WM_KEYDOWN and WM_SETFOCUS messages (see docs), to lock both mouse and keyboard button presses and prevent my control from focusing.

Second we create a derived control class based on the ListBox, in the same namespace for convenience:

public class LockableListbox : ListBox
{
    public bool Locked { get; set; }

    const int WM_LBUTTONDOWN = 0x0201;
    const int WM_SETFOCUS = 0x0007;
    const int WM_KEYDOWN = 0x0100;

    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    protected override void WndProc(ref Message m)
    {
        if (Locked)
            switch (m.Msg)
            {                
                case WM_LBUTTONDOWN:
                case WM_KEYDOWN:
                case WM_SETFOCUS:
                    return;
            }

        base.WndProc(ref m);
    }
}

Here the standard WndProc method of the control is overridden to stop chosen messages from posting depending on Lock flag state.

Third we just change ListBox to LockableListBox in our Form class designer part where it is required.

Now our modified ListBox will be protected from user actions (mouse clicks, keyboard actions and focusing) when the Lock property is set.

Related