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

标签 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";
    }

最佳答案

没有“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);
    }
  }

关于c# - 如何在 C# 中处理标签的拖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1733912/

相关文章:

jquery - 使用 jQuery 拖动 div 会导致页面突出显示

drag-and-drop - 在 Cappuccino 中捕捉到网格UI

c# - 自定义对象加法/减法

c# - 无法将 Serilog 配置代码行转换为 json 配置

winforms - Visual Studio 安装项目 - 安装时包含 .reg 文件

android: 拖放事件上的 java.lang.NoSuchMethodError setX

c# - 比较两列并在相同时增加计数

c# - 如何将 AverageTimer32 和 AverageBase 性能计数器与 System.Diagnostics.Stopwatch 一起使用?

.net - sendmessage api 选择组合框控件的特定索引

C# ShowDialog 调用另一个 ShowDialog