我正在尝试构建一个表单,用户可以在其中拖动标签并将其放在文本框上。我可以在文本框中找到一个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/