0
我有自定义控件,它是从PictureBox控件派生而来的。我想写一个KeyDown它的事件,我写了下面的代码,但我仍然无法使用它。请在下面检查我的代码,并指示我是否做错了什么或者需要更多补充。我知道有没有默认情况下KeyDown事件的图片框,因此我试图使自定义选择,能够与图片框keydown事件...为自定义控件编写keydown事件
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窗体应用程序V4工作。 0项目(非WPF)提交我的论文。
任何错误,异常,或者它只是不进入这些方法呢?没有thermethods打击,或只是一些? – J0HN
KeyDown事件并未完全执行,它甚至没有显示任何错误... –
我已测试过您的代码,OnKeyDown正在执行,但仅当您的控件具有焦点时,这是预期的行为。 –