3

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;
            }
    }
tomfox66
  • 329
  • 3
  • 10
  • 17

1 Answers1

8

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;
}
Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343