2010-09-26 104 views
0

我想不通为什么试图将文本从标准标签拖到记事本(或任何其他控件接受文本)不起作用。我看过文档和示例,但我没有看到问题。光标保持一个圆形,并且通过它的一条线,如果我注册一个FeedBack回调,事件总是NONE。创建一个标准的Windows窗体应用程序,放弃一个Label控件并注册MouseDown事件我有这个代码,我打电话给label1.DoDragDrop(label1,DragDropEffects.All | DragDropEffects.Link)。任何帮助,将不胜感激。从标准标签DoDragDrop不起作用

这里是我的表单代码:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace DragDropLabel 
{ 
    public partial class Form1 : Form 
    { 
     Point m_ClickLocation; 
     bool _bDragging = false; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void OnLabelMouseDown(object sender, MouseEventArgs e) 
     { 
      m_ClickLocation = e.Location; 
      _bDragging = true; 
     } 

     private void OnLabelMouseMove(object sender, MouseEventArgs e) 
     { 
      if (_bDragging) 
      { 
       Point pt = e.Location; 
       Size dragSize = SystemInformation.DragSize; 
       if (Math.Abs(pt.X - m_ClickLocation.X) > dragSize.Width/2 || 
        Math.Abs(pt.Y - m_ClickLocation.Y) > dragSize.Height/2) 
       { 
        DragDropEffects rc = label1.DoDragDrop(label1, DragDropEffects.All | DragDropEffects.Link); 
        _bDragging = false; 
       } 
      } 
     } 

    } 
} 

回答

1

标准编辑控件(文本框)不支持拖放&下降,将不接受任何下降的文字。

+0

我想从Control派生的任何控件支持拖放。该标签被用作拖放源而不是目标。 – AlanKley 2010-09-27 00:05:36

+0

@AlanKley:我意识到这一点。但是,标准文本框不接受拖放,因此您不能拖放它们。如果拖动到写字板或其他丰富的编辑控件,它应该可以正常工作。 – SLaks 2010-09-27 00:12:44

+0

感谢SLaks,如果我将Max建议的更改使用lable1.text而不是label1,那么您对写字板和记事本是正确的。 – AlanKley 2010-09-27 00:59:32

1

首先,更改

DragDropEffects rc = label1.DoDragDrop(label1, DragDropEffects.All | DragDropEffects.Link); 

label1.DoDragDrop(label1.Text, DragDropEffects.Copy); 

其次,你必须准备放置目标。让我们假设,它是文本框。下面是exmple扩展方法,这将允许通过调用MyTextBox.EnableTextDrop()到cofigure任何文本框:

static class TextBoxExtensions 
{ 
    public static void EnableTextDrop(this TextBox textBox) 
    { 
     if(textBox == null) throw new ArgumentNullException("textBox"); 

     // first, allow drop events to occur 
     textBox.AllowDrop = true; 
     // handle DragOver to provide visual feedback 
     textBox.DragOver += (sender, e) => 
      { 
       if(((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) && 
        e.Data.GetDataPresent(typeof(string))) 
       { 
        e.Effect = DragDropEffects.Copy; 
       } 
      }; 
     // handle DragDrop to set text 
     textBox.DragDrop += (sender, e) => 
      { 
       if(((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) && 
        e.Data.GetDataPresent(typeof(string))) 
       { 
        ((TextBox)sender).Text = (string)e.Data.GetData(typeof(string)); 
       } 
      }; 
    } 
} 
+0

谢谢Max。我没有实施放弃目标。我想放入其他应用程序编辑控制,记事本,extc。我错误地认为记事本是一个有效的放置目标,当它看起来不是。你正确地指出我需要传递label1.Text! – AlanKley 2010-09-27 01:01:05