C# 如何避免在单击所选文本时取消选择Winforms TextBox上的文本?

C# 如何避免在单击所选文本时取消选择Winforms TextBox上的文本?,c#,.net,winforms,drag-and-drop,C#,.net,Winforms,Drag And Drop,我想实现从TextBox到另一个控件的拖放操作。 问题是,当您选择文本的某一部分,然后单击文本框时,文本被取消选择。因此,当我在MouseDown事件中执行DoDragDrop时,textBox.SelectedText已为空 有没有办法避免这种行为?我发现了以下内容,但我不想失去仅拖放部分文本的可能性。我找到了解决方案。您需要继承文本框并覆盖OnMouseDown和WndProc: public class DragTextBox : TextBox { private string

我想实现从
TextBox
到另一个控件的拖放操作。 问题是,当您选择文本的某一部分,然后单击
文本框时,
文本被取消选择。因此,当我在
MouseDown
事件中执行
DoDragDrop
时,
textBox.SelectedText
已为空


有没有办法避免这种行为?我发现了以下内容,但我不想失去仅拖放部分文本的可能性。

我找到了解决方案。您需要继承文本框并覆盖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);
    }
}
原始代码作者帖子