tomfox66
tomfox66

Reputation: 329

How to disable listbox auto select item when pressing key

I have a listbox where I want to copy and paste items within that listbox. Copy and paste works fine but everytime I press "Crtl + C" the item starting with the letter C is automatically selected. Can this automatic selection be disabled or am I missing something here

Here is the copy and paste method I implemented:

    private void listBox_Script_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control == true && e.KeyCode == Keys.C)
        {
            int test = listBox_Script.SelectedIndex;                    
            Clipboard.SetDataObject(listBox_Script.Items[listBox_Script.SelectedIndex], true);
            return;
        }

        if (e.Control == true && e.KeyCode == Keys.V)
        {
            if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
            {
                listBox_Script.Items.Insert(listBox_Script.SelectedIndex + 1, Clipboard.GetDataObject().GetData(DataFormats.Text).ToString());
                return;
            }
    }

Upvotes: 3

Views: 3079

Answers (1)

Fredrik Mörk
Fredrik Mörk

Reputation: 158339

Did you try setting the SuppressKeyPress property of the KeyEventArgs object?

if (e.Control == true && e.KeyCode == Keys.C)
{
    int test = listBox_Script.SelectedIndex;                    
    Clipboard.SetDataObject(listBox_Script.Items[listBox_Script.SelectedIndex], true);
    e.SuppressKeyPress = true;
    return;
}

Upvotes: 8

Related Questions