我有自定义控件,它来自 PictureBox 控件。我想为它写一个 KeyDown 事件,我已经编写了下面的代码,但我仍然无法使用它。请检查下面的代码并告诉我,如果我做错了什么或需要更多的补充。我知道PictureBox没有默认的KeyDown事件,因此我正在尝试使用KeyDown事件制作一个自定义的可选PictureBox ...
using System;
using System.Linq;
using System.Windows.Forms;
namespace BenisImageDownloader
{
class SelectablePictureBox:PictureBox
{
public SelectablePictureBox()
{
this.SetStyle(ControlStyles.Selectable, true);
this.TabStop = true;
}
protected override void OnMouseDown(MouseEventArgs e)
{
this.Focus();
base.OnMouseDown(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
e.Handled = true;
base.OnKeyDown(e);
}
protected override bool IsInputKey(Keys keyData)
{
if (keyData == Keys.Up || keyData == Keys.Down) return true;
if (keyData == Keys.Left || keyData == Keys.Right) return true;
return base.IsInputKey(keyData);
}
protected override void OnEnter(EventArgs e)
{
this.Invalidate();
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
this.Invalidate();
base.OnLeave(e);
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (this.Focused)
{
var rc = this.ClientRectangle;
rc.Inflate(-2, -2);
ControlPaint.DrawFocusRectangle(pe.Graphics, rc);
}
}
}
}
我是一名从事Windows Form Application v4.0项目(不是WPF)的学生,我的论文要提交。
答案 0 :(得分:1)
您可以改写控件的ProcessCmdKey
()函数,并在那里捕获按键。
(抱歉,我只有一个VB示例 - 但你会得到这个想法):
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message,
ByVal keyData As System.Windows.Forms.Keys) As Boolean
'process key, return true for processed
If (keyData And Keys.KeyCode) = Keys.KeyToCheck Then
Return true
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function