今天做前台C#的同事,纠结在了,“拖拽事件使用的listBox1_MouseDown(s, e)会‘屏蔽掉’双击事件的使用的listBox1_DoubleClick”,这一问题上。查证多方资料,没好的解决方法。
于是笔者休息时实验了一下,使用e.Clicks这个属性可以解决。具体请参阅正文。
正文:
实现机理:((MouseEventArgs)e).Clicks通过值的{1, 2, ...}可以区分单击双击。于是可将双击事件实现写入e.Clicks > 1的语句,来达到预期效果。
细节不叨叨,直接上代码。
实验效果图如下:
于是笔者休息时实验了一下,使用e.Clicks这个属性可以解决。具体请参阅正文。
正文:
实现机理:((MouseEventArgs)e).Clicks通过值的{1, 2, ...}可以区分单击双击。于是可将双击事件实现写入e.Clicks > 1的语句,来达到预期效果。
细节不叨叨,直接上代码。
- 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 C4PlusWForm
- {
- public partial class Form2 : Form
- {
- public Form2()
- {
- InitializeComponent();
- }
- private void listBox1_MouseDown(object sender, MouseEventArgs e)
- {
- // 双击后触发动作
- if (e.Clicks > 1)
- {
- listBox2.Items.Add(listBox1.SelectedItem);
- listBox1.Items.Remove(listBox1.SelectedItem);
- System.Console.WriteLine("listBox1_MouseDown...DoubleClick");
- }
- // 单击动作
- else {
- int index = listBox1.IndexFromPoint(e.X, e.Y);
- string str = listBox1.Items[index].ToString();
- DragDropEffects ddeLb1 = DoDragDrop(str, DragDropEffects.All);
- if (ddeLb1 == DragDropEffects.All)
- {
- listBox1.Items.RemoveAt(listBox1.IndexFromPoint(e.X, e.Y));
- }
- }
- System.Console.WriteLine("listBox1_MouseDown" + e.Clicks);
- }
- private void listBox2_DragDrop(object sender, DragEventArgs e)
- {
- if (e.Data.GetDataPresent(DataFormats.StringFormat))
- {
- string str = (string)e.Data.GetData(
- DataFormats.StringFormat);
- listBox2.Items.Add(str);
- }
- }
- private void listBox2_DragOver(object sender, DragEventArgs e)
- {
- e.Effect = DragDropEffects.All;
- }
- private void listBox1_DoubleClick(object sender, EventArgs e)
- {
- System.Console.WriteLine("listBox1_DoubleClick");
- }
- }
- }
实验效果图如下: