无聊的时候 会做出无聊的事情, 项目中使用DateTimePicker控件时有客户提出能不能随鼠标上下滚动时 改变DateTimePicker控件对应的值,
本人当时就想出如下方案:
方案一: 获取鼠标焦点停在 DateTimePicker控件具体位置 (年、月、日|时、分、秒) , 那问题就可以很容易解决。
如果对应停靠在“年”上,那么我上下滚动时 就可通过日期函数对其年对应的值增或者减1,对应 “月、日、时、分、秒”同“年”一样处理。
—— 但几经琢磨 始终无法获取焦点停靠在DateTimePicker控件具体位置,只好暂时搁置改良此控件的想法。
当然 暂时搁置并不代表我放弃了改良DateTimePicker的想法,后面经过一次使用DateTimePicker控件是 发现 按 ↑ 和 ↓能改变 控件对应的值(值增或者减1),于是猛一蹦出方案2
方案二;
鼠标滚轮上下滚动时,对应触发 ↑ 和 ↓从而达到日期DateTimePicker控件对应的值(增或减)1 。
不啰嗦了 贴出代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DateTimePickerMouseWheel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control[] controls ={ dateTimePicker1 };
addDateTimePickerWheelEvent(controls);
}
public void addDateTimePickerWheelEvent(Control [] controls)
{
foreach (Control myControl in controls)
{
myControl.MouseWheel += new MouseEventHandler(DateTimePickerWheel_MouseWheel);
}
}
void DateTimePickerWheel_MouseWheel(object sender, MouseEventArgs e)
{
if (e.Delta < 0)//鼠标滚动轴往下滚
{
SendKeys.Send("{Down}");
}
else // 鼠标滚动轴 往上滚
{
SendKeys.Send("{Up}");
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//MessageBox.Show(e.KeyCode.ToString());
}
}
}
如有不足之处 望大家多多见谅!
源码免费下载:http://download.youkuaiyun.com/detail/wu_xiaowu7833/4027647