0

我正在尝试从列表框中拖动项目并将其放入文本框中。这对我来说可以。现在,当我尝试将第二个项目拖到同一个文本框中时,它会将其附加到文本框中包含的文本的最后一个。我希望它应该粘贴在我将项目拖入文本框的位置。到目前为止,我正在使用以下代码

private void Form1_Load(object sender, System.EventArgs e) {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0)
                listBoxControl1.Items.Add("Item " + i.ToString());
         }

 private void listBoxControl1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) {
        ListBoxControl c = sender as ListBoxControl;
        p = new Point(e.X, e.Y);
        int selectedIndex = c.IndexFromPoint(p);
        if (selectedIndex == -1)
            p = Point.Empty;
    }

    private void listBoxControl1_MouseMove(object sender,System.Windows.Forms.MouseEventArgs e) {
        if (e.Button == MouseButtons.Left)
            if ((p != Point.Empty) && ((Math.Abs(e.X - p.X) > 5) || (Math.Abs(e.Y - p.Y) > 5)))
                listBoxControl1.DoDragDrop(sender, DragDropEffects.Move);            
    }


    private void textEdit1_DragOver(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Move;
    }

  private void textEdit1_DragDrop(object sender, DragEventArgs e)
    {
        TextEdit textBox1 = sender as TextEdit;
        Point newPoint = new Point(e.X, e.Y);
        newPoint = textBox1.PointToClient(newPoint);                          
        object item = listBoxControl1.Items[listBoxControl1.IndexFromPoint(p)];

        if (textBox1.Text == "")
        {
            textBox1.Text = item.ToString();
        }
        else
        {
            textBox1.Text = textBox1.Text + "," + item.ToString();
        }
        listBoxControl1.Items.Remove(item);
    }
4

1 回答 1

1

我使用 TextBox 而不是 TextEdit ,试试这个代码

    private void textBox1_DragDrop(object sender, DragEventArgs e)
    {
        TextBox textBox1 = sender as TextBox;
        Point newPoint = new Point(e.X, e.Y);
        newPoint = textBox1.PointToClient(newPoint);
        int index = textBox1.GetCharIndexFromPosition(newPoint);

        object item = listBox1.Items[listBox1.IndexFromPoint(p)];

        if (textBox1.Text == "")
        {
            textBox1.Text = item.ToString();
        }
        else
        {
            var text = textBox1.Text;
            var lastCharPosition = textBox1.GetPositionFromCharIndex(index);
            if (lastCharPosition.X < newPoint.X)
            {
                text += item.ToString();
            }
            else
            {
                text = text.Insert(index, item.ToString());
            }

            textBox1.Text = text;
        }
        listBox1.Items.Remove(item);
    }
于 2013-03-15T07:27:03.737 回答