C#内TextBox的Drog&Drop拖放操作
作者:C/S框架网  发布日期:2011/07/14 21:19:25
C#内TextBox的Drog&Drop拖放操作

相信大家都做过Drog&Drop拖放.比如拖放文件,拖放TreeNode,ListView,但对TextBox的Drog&Drop拖放操作有个问题: 在MouseDown事件中调用DoDragDrop方法,因为鼠标一下去选中的文本就没有了!

其实解决的重点是如何控制即选中文本又可以拖放。

可以这么解决:

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

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

在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; //注意,这里要还原变量,否则无休止托放
}





C/S框架网|原创精神.创造价值.打造精品


扫一扫加作者微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务


上一篇 下一篇