Samy Dressel
Samy Dressel

Reputation: 143

Preventing ListView from Scrolling/Selecting Items when Pressing Keys

I tried to prevent my ListView from automatically scrolling down/selecting Item with the first letter I pressed.

So I tried to override it but this just doesn't work me.

public ref class ExtendedListView : public System::Windows::Forms::ListView
{
public:
    ExtendedListView();

    virtual void KeyPress(KeyEventArgs e) override
    {
        if (e.KeyCode == Keys::W || e.KeyCode == Keys::A || e.KeyCode == Keys::S || e.KeyCode == Keys::D)
        {
            MessageBox::Show("Test");
            return;
        }           
    }

};

(I added the MessageBox to test if it works)

Upvotes: 0

Views: 142

Answers (2)

xMRi
xMRi

Reputation: 15375

Just use the SuppressKeyPress from the KeyEventArgs

This should cause that the control ignores this key.

Upvotes: 1

Sabouei Alireza
Sabouei Alireza

Reputation: 97

the 'KeyPress' event fires before the change in listview (I tired it with list box) The trick is to define 2 variables:

int selectedindex=0;
bool goBack=false;

private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode==Keys.B)
    {
        selectedindex = listBox1.SelectedIndex;
        goBack = true;
    }
}

private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
    if (goBack)
    {
        listBox1.SelectedIndex = selectedindex;
        goBack = false;
    }
}

This sample prevents the 'B' key for example. I hope that is what u mean.

Upvotes: 2

Related Questions