使PictureBox不会失去对箭头键的关注?

时间:2010-08-03 14:47:59

标签: winforms

This question除了我想问我如何让我的图片框不要忽视箭头键的按键。当我重载它并设置TabStop = true时它会得到焦点,但是箭头键给我带来了问题。

1 个答案:

答案 0 :(得分:6)

这需要覆盖控件的IsInputKey()方法。需要进行相当多的额外手术才能让图片框首先获得焦点。首先在项目中添加一个新类,使其看起来类似于:

using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;

class MyPictureBox : PictureBox {
    public MyPictureBox() {
        SetStyle(ControlStyles.Selectable, true);
        SetStyle(ControlStyles.UserMouse, true);
        this.TabStop = true;
    }
}

这可确保控件可以获得焦点并可以选项卡。接下来,您必须撤消TabStop和TabIndex属性的属性,以便用户可以设置Tab键顺序:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public new int TabIndex {  
    get { return base.TabIndex; }
    set { base.TabIndex = value; }
}

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public new bool TabStop {
    get { return base.TabStop; }
    set { base.TabStop = value; }
}

接下来,您必须向用户说明控件具有焦点,以便她知道操作光标键时会发生什么:

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) {
        Rectangle rc = this.DisplayRectangle;
        rc.Inflate(-2, -2);
        ControlPaint.DrawFocusRectangle(pe.Graphics, rc);
    }
}

最后,您重写IsInputKey(),以便控件可以看到箭头键:

protected override bool IsInputKey(Keys keyData) {
    if (keyData == Keys.Up || keyData == Keys.Down ||
        keyData == Keys.Left || keyData == Keys.Right) return true;
    return base.IsInputKey(keyData);
}

编译。将新控件从工具箱顶部拖放到表单上。