winform textBox数据拖放

 

using System;
using System.Windows.Forms;

namespace UseControl
{
    public sealed class TextBox : System.Windows.Forms.TextBox
    {
        protected override void InitLayout()
        {
            base.InitLayout();
            this.AllowDrop = true;
        }

        private bool MouseIsDown = false;

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            MouseIsDown = true;
        }

        protected override void OnMouseUp(MouseEventArgs mevent)
        {
            base.OnMouseUp(mevent);
            MouseIsDown = false;
        }

        /// <summary>
        /// 开始拖放操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (MouseIsDown){
                if (e.X == 0 || e.Y == 0 || e.Y == this.Height)
                {
                    this.DoDragDrop(this.SelectedText, DragDropEffects.Copy);
                }
            }
        }

        /// <summary>
        /// 拖放完成时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            base.OnDragDrop(drgevent);
            //获取包含此事件关联的数据
            this.Text = (this.SelectionLength > 0) ? this.Text.Substring(0, this.SelectionStart) + drgevent.Data.GetData(DataFormats.Text).ToString() +
                this.Text.Substring(this.SelectionStart+this.SelectionLength) : this.Text.Insert(this.SelectionStart, drgevent.Data.GetData(DataFormats.Text).ToString());
            drgevent.Data.SetData("");
        }

        /// <summary>
        /// 用鼠标将某项拖到该控件工作区时发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnDragEnter(DragEventArgs drgevent)
        {
            base.OnDragEnter(drgevent);
            //指定拖放的效果
            drgevent.Effect = drgevent.Data.GetDataPresent(DataFormats.Text) ? DragDropEffects.Copy : DragDropEffects.None;
        }
    }
}

你可能感兴趣的:(winform textBox数据拖放)