在winform中Form的KeyDown,KeyPress,KeyUp三个键盘事件,只可以捕获字符键,而不可以捕获TAB,HOME,UP,DOWN等控制键。如果要使用这几个键,可以重写Control的ProcessDialogKey方法,在此方法中可以做相关的事件处理。
例如下面的一段代码是CSS背景图合并工具中用户控制图片上下左右移动位置的代码
protected
override
bool
ProcessDialogKey(Keys keyData)
{
if (_selectedPicture != null )
{
switch (keyData)
{
case Keys.Left:
if (_selectedPicture.Location.X > 0 ) _selectedPicture.Location = new Point(_selectedPicture.Location.X - 1 , _selectedPicture.Location.Y);
break ;
case Keys.Right:
_selectedPicture.Location = new Point(_selectedPicture.Location.X + 1 , _selectedPicture.Location.Y);
break ;
case Keys.Up:
if (_selectedPicture.Location.Y > 0 ) _selectedPicture.Location = new Point(_selectedPicture.Location.X, _selectedPicture.Location.Y - 1 );
break ;
case Keys.Down:
_selectedPicture.Location = new Point(_selectedPicture.Location.X, _selectedPicture.Location.Y + 1 );
break ;
default :
break ;
}
}
return base .ProcessDialogKey(keyData);
}
{
if (_selectedPicture != null )
{
switch (keyData)
{
case Keys.Left:
if (_selectedPicture.Location.X > 0 ) _selectedPicture.Location = new Point(_selectedPicture.Location.X - 1 , _selectedPicture.Location.Y);
break ;
case Keys.Right:
_selectedPicture.Location = new Point(_selectedPicture.Location.X + 1 , _selectedPicture.Location.Y);
break ;
case Keys.Up:
if (_selectedPicture.Location.Y > 0 ) _selectedPicture.Location = new Point(_selectedPicture.Location.X, _selectedPicture.Location.Y - 1 );
break ;
case Keys.Down:
_selectedPicture.Location = new Point(_selectedPicture.Location.X, _selectedPicture.Location.Y + 1 );
break ;
default :
break ;
}
}
return base .ProcessDialogKey(keyData);
}