我继续在我的简单图形程序中(使用 C#)编写某种键盘导航。而我又遇到了麻烦。
我的问题是我想处理键盘输入以移动图层。用鼠标移动图层已经可以很好地工作,但控件没有获得焦点(此控件既不会触发 KeyUp/KeyDown/KeyPress 也不会触发 GotFocus/LostFocus)。
由于我的类派生自Panel(并覆盖了几个事件),因此我也覆盖了上面提到的事件,但我无法成功触发这些事件。
我想我可以使用 Keyboard.GetState() 或 ProcessCmdWnd 之类的东西来实现键盘响应。但是:我仍然必须能够判断控件何时获得焦点。
是否有一种或多或少优雅的方式将此功能添加到用户控件(基于面板)?
我在这里检查了很多线程,我可能会使用这种方法 https://stackoverflow.com/questions/902767/c-tetris-clone-cant-get-block-to-respond-properly-to-arrow-key-combinations用于键盘输入。然而焦点问题仍然存在。
非常感谢您提前提供信息!
Igor.
p.s.:我正在使用 VS2008 使用 C# .NET v3.5 进行编程。这是一个 Windows.Forms 应用程序,not WPF.
Panel 类被设计为容器,它避免获取焦点,因此子控件将始终获得焦点。你需要做一些手术来解决这个问题。我还添加了代码以在 KeyDown 事件中获取光标击键:
using System;
using System.Drawing;
using System.Windows.Forms;
class SelectablePanel : Panel {
public SelectablePanel() {
this.SetStyle(ControlStyles.Selectable, true);
this.TabStop = true;
}
protected override void OnMouseDown(MouseEventArgs e) {
this.Focus();
base.OnMouseDown(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);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)