覆盖粘贴操作ListBox

时间:2012-09-03 12:12:59

标签: c# winforms listbox

当用户粘贴到ListBox中时,我希望剪贴板中的内容被安排为单独的项目。拆分文本将由换行符完成。

1 个答案:

答案 0 :(得分:0)

如果您对表单ListBox有控制权(让我们称之为listBox),您应该处理其KeyDown事件。

以下是示例:

private void listBox_KeyDown(object sender, KeyEventArgs e)
{
    // Check that the button pressed is V, that Control is also pressed and that the clipboard contains text.
    if ((e.KeyCode == Keys.V) && e.Control && Clipboard.ContainsText())
    {
        // Get text from clipboard and separate it.
        string text = Clipboard.GetText();
        string[] textLines = text.Split(
            new string[] { Environment.NewLine }, 
            StringSplitOptions.RemoveEmptyEntries); // or don't

        // Add lines to listBox items.
        listBox.Items.AddRange(textLines);

        // Mark event as handled.
        e.Handled = true;
    }
}