解决Winform的ComboBox下拉框鼠标双击事件无效的问题

您所在的位置:网站首页 comboBox控件触发事件 解决Winform的ComboBox下拉框鼠标双击事件无效的问题

解决Winform的ComboBox下拉框鼠标双击事件无效的问题

2023-04-01 01:14| 来源: 网络整理| 查看: 265

今天碰到一个需求:就是鼠标双击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 { /// /// 设置ComboBox控件鼠标双击业务逻辑 /// /// public void SetComboBoxControlMouseDouble(List cmbList) { if (cmbList == null || cmbList.Count == 0) return; foreach (var item in cmbList) { item.MouseClick += Cmb_MouseClick; } } private DateTime dtCmbDeptLastClick = DateTime.MinValue; /// /// 鼠标单击 /// /// /// 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); } /// /// 鼠标双击 /// /// /// private void Cmb_DoubleMouseClick(object sender, MouseEventArgs e) { MessageBox.Show("鼠标双击:"+(sender as ComboBox).Name); } /// /// ComboBox的属性信息 /// /// /// 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() { this.comboBox1,this.comboBox2}); this.comboBox1.DroppedDown = true; } } }

 目前是批量ComboBox注册鼠标双击事件,代码比较简单,就不解释了。

4 运行结果如下:

好了,本文到此结束 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3