如何处理在C#中拖动标签?

时间:2009-11-14 10:37:28

标签: c# winforms drag-and-drop

我正在尝试构建一个表单,用户可以在其中拖动标签并将其放在文本框中。我可以在文本框中找到AllowDrop,但标签中没有“AllowDrag”等属性。此外,我为所有拖拉机创建了方法。删除标签的事件(DragEnter,DragLeave等),但它们似乎都不起作用。我无法弄清楚如何拖动。我该如何处理?

        private void label1_Click(object sender, EventArgs e)
    {

        // This one works
        status.Text = "Click";
    }

        private void label1_DragOver(object sender, DragEventArgs e)
    {

        // this and the others do not
        status.Text = "DragOver";
    }

    private void label1_GiveFeedback(object sender, GiveFeedbackEventArgs e)
    {
        status.Text = "GiveFeedback";
    }

    private void label1_DragDrop(object sender, DragEventArgs e)
    {
        status.Text = "DragDrop";
    }

    private void label1_DragEnter(object sender, DragEventArgs e)
    {
        status.Text = "DragEnter";
    }

    private void label1_DragLeave(object sender, EventArgs e)
    {
        status.Text = "DragLeave";
    }

    private void label1_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
    {
        status.Text = "QueryContinueDrag";
    }

2 个答案:

答案 0 :(得分:16)

没有“AllowDrag”属性,您使用DoDragDrop()方法主动启动D + D.事件处理程序需要在D + D目标上,而不是源。一个示例表单,它需要一个标签和一个文本框:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      label1.MouseDown += new MouseEventHandler(label1_MouseDown);
      textBox1.AllowDrop = true;
      textBox1.DragEnter += new DragEventHandler(textBox1_DragEnter);
      textBox1.DragDrop += new DragEventHandler(textBox1_DragDrop);
    }

    void label1_MouseDown(object sender, MouseEventArgs e) {
      DoDragDrop(label1.Text, DragDropEffects.Copy);
    }
    void textBox1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.Text)) e.Effect = DragDropEffects.Copy;
    }
    void textBox1_DragDrop(object sender, DragEventArgs e) {
      textBox1.Text = (string)e.Data.GetData(DataFormats.Text);
    }
  }

答案 1 :(得分:2)

你必须手动移动标签,方法是按下你按下按钮时生成的bool,当你松开按钮时保持错误;在你的mousemove事件中,当bool为真时你将控制移动到鼠标。

您可以找到示例here