【问题标题】:How to avoid deselecting text on Winforms TextBox when clicking on selected text?单击选定文本时如何避免取消选择 Winforms TextBox 上的文本?
【发布时间】:2012-01-11 12:02:18
【问题描述】:
我想实现从TextBox 到另一个控件的拖放操作。
问题是当您选择文本的某些部分然后单击TextBox 时,文本被取消选择。因此,当我在MouseDown 事件中执行DoDragDrop 时,textBox.SelectedText 已经为空。
有没有办法避免这种行为?我发现关注了example,但我不想放弃仅拖放部分文本的可能性。
【问题讨论】:
标签:
c#
.net
winforms
drag-and-drop
【解决方案1】:
我找到了解决方案。你需要继承TextBox并覆盖OnMouseDown和WndProc:
public class DragTextBox : TextBox
{
private string dragText;
private const int WM_LBUTTONDOWN = 0x201;
protected override void OnMouseDown(MouseEventArgs e)
{
if (dragText.Length > 0)
{
SelectionStart = Text.IndexOf(dragText);
SelectionLength = dragText.Length;
DoDragDrop(dragText, DragDropEffects.Copy);
SelectionLength = 0;
}
base.OnMouseDown(e);
}
protected override void WndProc(ref Message m)
{
if ((m.Msg == WM_LBUTTONDOWN))
dragText = SelectedText;
base.WndProc(ref m);
}
}
原代码作者发帖here