C#内TextBox的Drog&Drop拖放操作
C#内TextBox的Drog&Drop拖放操作相信大家都做过Drog&Drop拖放.比如拖放文件,拖放TreeNode,ListView,但对TextBox的Drog&Drop拖放操作有个问题: 在MouseDown事件中调用DoDragDrop方法,因为鼠标一下去选中的文本就没有了!
其实解决的重点是如何控制即选中文本又可以拖放。
可以这么解决:
1.在TextBox的MouseUp时将选中的文本保存的TextBox.Tag属性中.
2.在MouseDown开始拖放时,然后还原Selection.
我们定义一个类用于记录MouseUp时的状态:
在TextBox的MouseUp时将选中的文本保存的TextBox.Tag属性中.
在MouseDown开始拖放时,然后还原Selection.现在可能将选中的文本拖放到任一支持AllowDrop的控件中了。

扫一扫加作者微信

其实解决的重点是如何控制即选中文本又可以拖放。
可以这么解决:
1.在TextBox的MouseUp时将选中的文本保存的TextBox.Tag属性中.
2.在MouseDown开始拖放时,然后还原Selection.
我们定义一个类用于记录MouseUp时的状态:
public class DropData
{
public string _text;
public int _start;
public int _len;
public DropData(string text, int start, int len)
{
_text = text;
_start = start;
_len = len;
}
}
{
public string _text;
public int _start;
public int _len;
public DropData(string text, int start, int len)
{
_text = text;
_start = start;
_len = len;
}
}
在TextBox的MouseUp时将选中的文本保存的TextBox.Tag属性中.
private void textBox1_MouseUp(object sender, MouseEventArgs e)
{
if (textBox1.SelectedText != "")
{
DropData d = new DropData(textBox1.SelectedText, textBox1.SelectionStart, textBox1.SelectionLength);
textBox1.Tag = d;
}
}
{
if (textBox1.SelectedText != "")
{
DropData d = new DropData(textBox1.SelectedText, textBox1.SelectionStart, textBox1.SelectionLength);
textBox1.Tag = d;
}
}
在MouseDown开始拖放时,然后还原Selection.现在可能将选中的文本拖放到任一支持AllowDrop的控件中了。
private void textBox1_MouseDown(object sender, MouseEventArgs e)
{
if (textBox1.Tag == null) return;
if (textBox1.Tag is DropData)
{
DropData d = textBox1.Tag as DropData;
textBox1.SelectionStart = d._start;
textBox1.SelectionLength = d._len;
textBox1.DoDragDrop(d._text, DragDropEffects.Copy);
}
textBox1.Tag = null; //注意,这里要还原变量,否则无休止托放
}
{
if (textBox1.Tag == null) return;
if (textBox1.Tag is DropData)
{
DropData d = textBox1.Tag as DropData;
textBox1.SelectionStart = d._start;
textBox1.SelectionLength = d._len;
textBox1.DoDragDrop(d._text, DragDropEffects.Copy);
}
textBox1.Tag = null; //注意,这里要还原变量,否则无休止托放
}

扫一扫加作者微信


版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网