I have custom control which is derived from PictureBox control. I wanna write a KeyDown Event for it and I’ve written the code below and still I’m not being able to use it. Please check my code below and instruct me if I’m doing anything wrong or any more additions are required. I know there is no by default KeyDown event for PictureBox and so I’m trying to make a custom Select-able PictureBox with KeyDown Event…
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);
}
}
}
}
I’m a student working on Windows Form Application v4.0 project(not WPF) for my papers to be submitted.
You can override the control’s
ProcessCmdKey() function instead and capture the key-presses there.(sorry, I only have a VB example – but you’ll get the idea):