问题描述
我将继续在我的简单图形程序(使用 C#)中编写某种键盘导航.我又遇到了麻烦.
I am continuing to program some kind of keyboard navigation in my simple graphic program (using C#). And I ran into trouble once again.
我的问题是我想处理键盘输入以移动图层.用鼠标移动图层已经很好用了,但是控件没有获得焦点(KeyUp/KeyDown/KeyPress 和 GotFocus/LostFocus 都没有为此控件触发).由于我的类派生自 Panel(并覆盖了几个事件),我也覆盖了上面提到的事件,但我无法成功触发这些事件.
My problem is that I want to process the keyboard input to move a layer around. Moving the layer with the mouse already works quite well, yet the control doesn't get the focus (neither KeyUp/KeyDown/KeyPress nor GotFocus/LostFocus is triggered for this control). Since my class derives from Panel (and overwrites a couple of events), I've also overwritten the events mentioned above, but I can't succeed in getting those events triggered.
我想我可以使用 Keyboard.GetState() 或 ProcessCmdWnd 之类的东西来实现键盘响应.但是:我仍然必须能够判断控件何时获得焦点.
I think I could manage to implement keyboard response either using something like Keyboard.GetState() or ProcessCmdWnd or something. However: I still have to be able to tell when the control got the focus.
是否有或多或少优雅的方式将此功能添加到用户控件(基于 Panel)?
我在这里检查了很多线程,我可能会使用 这种方法用于键盘输入.然而,焦点问题仍然存在.
I've checked many threads in here and I might use this approach for keyboard input. The focus problem however still remains.
非常感谢您提前提供信息!
Thank you very much for information in advance!
伊戈尔.
p.s.:我正在使用 VS2008 在 C# .NET v3.5 中编程.这是一个 Windows.Forms 应用程序,不是 WPF.
p.s.: I am programming in C# .NET v3.5, using VS2008. It's a Windows.Forms application, not WPF.
推荐答案
Panel 类被设计为容器,它避免了获取焦点,因此子控件将始终获取它.你需要做一些手术来解决这个问题.我还在 KeyDown 事件中输入了代码以获取光标击键:
The Panel class was designed as container, it avoids taking the focus so a child control will always get it. You'll need some surgery to fix that. I threw in the code to get cursor key strokes in the KeyDown event as well:
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);
}
}
}
这篇关于面板没有得到焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!