how to drag and drop a word from a textbox into another at a particular location in c#

妖精的绣舞 提交于 2019-12-11 07:53:03

问题


I have a slight problem when it comes to drag dropping text from a C# winforms app.

I want to Drag the contents from "TextBoxA" and Drop it into a particular location in "TextBoxB".

e.g.

TextBoxA.Text = "Big "
TextBoxB.Text = "Hello World"

When dragging "Big" from TextBoxA and dropping it in between "Hello World" from TextBoxB, TextBoxB would end up something like: "Hello Big World"(dependant on where the mouse is released ).


回答1:


I hope this example will help you.




回答2:


I recognise this is a very old question, but thought it still worth answering.

The comments in the code below are pretty self-explanatory – let me know if you have any questions.

    public Form1()
    {
        InitializeComponent();

        // Allow TextBoxB to accept a drop.
        TextBoxB.AllowDrop = true;

        // Add event handlers to manage the drag drop action.
        TextBoxB.DragEnter += TextBoxB_DragEnter;
        TextBoxB.DragDrop += TextBoxB_DragDrop;
    }

    void TextBoxB_DragEnter(object sender, DragEventArgs e)
    {
        // Update cursor to inform user of drag drop action.
        if (e.Data.GetDataPresent(DataFormats.Text)) e.Effect = DragDropEffects.Copy;
    }

    void TextBoxB_DragDrop(object sender, DragEventArgs e)
    {
        // Get the current cursor postion within the control.
        var point =TextBoxB.PointToClient(Cursor.Position);

        // Find the character index based on cursor position.
        var pos = TextBoxB.GetCharIndexFromPosition(point);

        // Insert the required text into the control.
        TextBoxB.Text = TextBoxB.Text.Insert(pos, TextBoxA.Text);
    }


来源:https://stackoverflow.com/questions/9717083/how-to-drag-and-drop-a-word-from-a-textbox-into-another-at-a-particular-location

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!