问题描述
从C#winforms应用程序拖放文本时,我有一个小问题。
我想从 TextBoxA中拖动内容并将其拖放到
例如
TextBoxA。
例如
TextBoxA。 Text = Big
TextBoxB.Text = Hello World
当拖动 Big ,然后将其放在TextBoxB的 Hello World之间,TextBoxB最终将类似于: Hello Big World(取决于释放鼠标的位置)。
解决方案我知道这是一个非常老的问题,但认为它仍然值得回答。
下面的代码中的注释是
public Form1()
{
InitializeComponent();
//允许TextBoxB接受放置。
TextBoxB.AllowDrop = true;
//添加事件处理程序以管理拖放操作。
TextBoxB.DragEnter + = TextBoxB_DragEnter;
TextBoxB.DragDrop + = TextBoxB_DragDrop;
}
void TextBoxB_DragEnter(object sender,DragEventArgs e)
{
//更新光标以通知用户拖放操作。
if(e.Data.GetDataPresent(DataFormats.Text))e.Effect = DragDropEffects.Copy;
}
void TextBoxB_DragDrop(object sender,DragEventArgs e)
{
//获取控件中的当前光标位置。
var point = TextBoxB.PointToClient(Cursor.Position);
//根据光标位置查找字符索引。
var pos = TextBoxB.GetCharIndexFromPosition(point);
//将所需的文本插入控件。
TextBoxB.Text = TextBoxB.Text.Insert(pos,TextBoxA.Text);
}
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 ).
解决方案 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);
}
这篇关于如何在C#中将单词从文本框中拖放到另一个特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!