C#中两个listBox双击与拖放共存的一种实现

[b]引言:[/b]
今天做前台C#的同事,纠结在了,“拖拽事件使用的listBox1_MouseDown(s, e)会‘屏蔽掉’双击事件的使用的listBox1_DoubleClick”,这一问题上。查证多方资料,没好的解决方法。
于是笔者休息时实验了一下,使用e.Clicks这个属性可以解决。具体请参阅正文。

[b]正文:[/b]
实现机理:((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");
}

}
}


实验效果图如下:
[img]http://dl.iteye.com/upload/attachment/0067/5083/9b7b389e-7515-30cf-9612-e425f4494958.gif[/img]
操作步骤:
0)选中222
1)拖动222
2)双击333
3)双击1111
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值