将文本插入文本框中的x,y坐标位置

时间:2013-03-15 06:09:49

标签: c# winforms textbox

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

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);
    }

1 个答案:

答案 0 :(得分: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);
    }