小组没有得到焦点

问题描述:

我继续(使用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 /按键preSS也没有的GotFocus /引发LostFocus触发此控件)。
由于我的类从面板派生(并覆盖一对夫妇的事件),我也覆盖上述事件,但我不能让这些事件触发的成功。

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.

是否有或多或少的优雅的方式来增加这种能力的用户控件(这是基于面板)?

我在这里检查多个线程和我可能会使用this接近键盘输入。然而,焦点问题仍然存在。

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:我编程在C#.NET v3.5版本,使用VS2008。这是一个Windows.Forms的应用程序,不是WPF

p.s.: I am programming in C# .NET v3.5, using VS2008. It's a Windows.Forms application, not WPF.

Panel类被设计成容器,它避免服用焦点,这样子控件总是会得到它。你需要一些手术修复。我在code扔得到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);
        }
    }
}