【问题标题】:Dropping text at mouse position in textbox在文本框中的鼠标位置放置文本
【发布时间】:2014-12-25 20:37:41
【问题描述】:

尽管有很多类似的问题,但我还是找不到答案。我想做的是:

我有一个带有一些文本的文本框和几个带有图片的图片框。如果我执行从图片到文本框的拖放操作,一些文本应该插入到文本框中,在我进行拖放时光标所在的位置(即 mouseup 事件发生的位置)。

第一部分很好:

private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
    // Create custom text ...
    pictureBox1.DoDragDrop("Some custom text", DragDropEffects.Copy);
}

private void textBox1_DragEnter(object sender, DragEventArgs e) {
    if (e.Data.GetDataPresent(DataFormats.Text))
        e.Effect = DragDropEffects.Copy;
    else
        e.Effect = DragDropEffects.None;
}

我的问题是如何定义放置文本的位置:

private void textBox1_DragDrop(object sender, DragEventArgs e) {
        textBox1.Text.Insert(CORRECT_POSITION, e.Data.GetData(DataFormats.Text).ToString());
    }

有什么建议吗?

编辑:我尝试使用 GetCharIndexFromPosition() 获得正确的位置,但它似乎没有返回正确的位置。下面的代码确实返回了一个字符位置,但我不知道它是从哪里得到的。很明显,它并不代表光标的位置。

private void textBox1_DragDrop(object sender, DragEventArgs e) {
    TextBox textBox1 = (TextBox)sender;
    System.Drawing.Point position = new System.Drawing.Point(e.X, e.Y);
    int index = textBox1.GetCharIndexFromPosition(position);
    MessageBox.Show(index.ToString());
}

【问题讨论】:

  • 感谢@linurb 的中肯问题!

标签: c# textbox drag-and-drop cursor-position


【解决方案1】:

您需要将当前鼠标位置转换为文本框内的客户端坐标。此外,您可以在 DragOver() 事件中移动插入点,以便用户可以看到将插入文本的位置:

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            pictureBox1.DoDragDrop("duck", DragDropEffects.Copy);
        }
    }

    void textBox1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.Text))
            e.Effect = DragDropEffects.All;
        else
            e.Effect = DragDropEffects.None;
    }

    void textBox1_DragOver(object sender, DragEventArgs e)
    {
        int index = textBox1.GetCharIndexFromPosition(textBox1.PointToClient(Cursor.Position));
        textBox1.SelectionStart = index;
        textBox1.SelectionLength = 0;
    }

    void textBox1_DragDrop(object sender, DragEventArgs e)
    {
        string txt = e.Data.GetData(DataFormats.Text).ToString();
        int index = textBox1.GetCharIndexFromPosition(textBox1.PointToClient(Cursor.Position));
        textBox1.SelectionStart = index;
        textBox1.SelectionLength = 0;
        textBox1.SelectedText = txt;
    }

【讨论】:

  • 太好了,谢谢!我也得到了奖金部分,虽然我不明白鸭子部分。 :) 如果没有 MouseMove 事件(?),它似乎也能正常工作。
  • MouseMove() 事件只是启动拖放的另一种方式。
  • 很好,但是……你真的应该使用DataFormats.UnicodeText
  • 由于某种原因,我无法将其放在文本框的最终索引上...知道为什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多