今天碰到一个需求:就是鼠标双击ComboBox后,然后模拟键盘空格键按下,测试发现,在ComboBox可以展开下拉框的情况下,鼠标双击事件是没有用的。想要实现鼠标双击事件,需要利用到鼠标单击事件,在鼠标单击事件中判断(当前时间减去上一次单击的时间)是否小于某个值(如200毫秒),则认为是用户进行了鼠标双击。
在做的过程中又额外增加了一个要求,某些ComboBox在鼠标点击时就能展开下拉列表,而不用点击ComboBox后面的下拉小箭头。要点击鼠标就能展开ComboBox的选项,这就需要在鼠标单击事件中把ComboBox的属性DroppedDown设置为True
注意:其中踩了一个很冤的坑,计算两个时间间隔的总毫秒,用了TimeSpan的Milliseconds,其实是不对的,Milliseconds计算的是TimeSpan秒数部分的值,应该是TimeSpan的TotalMilliseconds
测试环境:
vistual studio 2017
.net framework 4.0
测试步骤如下:
1 新增winfrom项目,名为:WindowsFormsApp1
2 在界面中拖入两个ComboBox控件,名称为comboBox1和comboBox2,布局如下图:
设置comboBox1和comboBox2的下拉选项值如下图:
3 新增类ComboBoxBp并编辑如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public class ComboBoxBp
{
/// <summary>
/// 设置ComboBox控件鼠标双击业务逻辑
/// </summary>
/// <param name="cmbList"></param>
public void SetComboBoxControlMouseDouble(List<ComboBox> cmbList)
{
if (cmbList == null || cmbList.Count == 0) return;
foreach (var item in cmbList)
{
item.MouseClick += Cmb_MouseClick;
}
}
private DateTime dtCmbDeptLastClick = DateTime.MinValue;
/// <summary>
/// 鼠标单击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Cmb_MouseClick(object sender, MouseEventArgs e)
{
double gapMillises = (DateTime.Now - dtCmbDeptLastClick).TotalMilliseconds;
//SystemInformation.DoubleClickTime的值为300
if (gapMillises < SystemInformation.DoubleClickTime)
{
Cmb_DoubleMouseClick(sender, e);
}
dtCmbDeptLastClick = DateTime.Now;
GetTestMessage(sender, e);
}
/// <summary>
/// 鼠标双击
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Cmb_DoubleMouseClick(object sender, MouseEventArgs e)
{
MessageBox.Show("鼠标双击:"+(sender as ComboBox).Name);
}
/// <summary>
/// ComboBox的属性信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GetTestMessage(object sender, MouseEventArgs e)
{
//ComboBox comboBox = sender as ComboBox;
//if (comboBox != null)
//{
// int comboWidth = comboBox.Width - 20;
// if (e.Location.X > comboWidth && comboWidth > 0) return;
// int mouseY = e.Y;
// if (mouseY > comboBox.Height) return;
//}
//e.Location.X的值等于comboBox.Width e.Location.Y等于comboBox.Height
}
}
}
Form1的代码如下:
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 WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new ComboBoxBp().SetComboBoxControlMouseDouble(new List<ComboBox>() { this.comboBox1,this.comboBox2});
this.comboBox1.DroppedDown = true;
}
}
}
目前是批量ComboBox注册鼠标双击事件,代码比较简单,就不解释了。
4 运行结果如下:
文章来源:https://www.toymoban.com/news/detail-526294.html
好了,本文到此结束 文章来源地址https://www.toymoban.com/news/detail-526294.html
到了这里,关于解决Winform的ComboBox下拉框鼠标双击事件无效的问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!