开发者

Make a PictureBox not lose focus on Arrow Keys?

This question except i want to ask how do i make my picturebox not lose开发者_如何学Python focus on keypress of the arrow keys. It gets focus when i overloaded it and set TabStop = true but the arrow keys are giving me problems.


That requires overriding the control's IsInputKey() method. Quite a bit of additional surgery is required to let the picture box get the focus in the first place. Start by adding a new class to your project, make it look similar to this:

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;
    }
}

This ensures that the control can get the focus and can be tabbed to. Next, you'll have to undo the attributes for the TabStop and TabIndex properties so the user can set the tab order:

[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; }
}

Next, you have to make it clear to the user that the control has the focus so she'll know what to expect when operating the cursor keys:

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);
    }
}

And finally you override IsInputKey() so that the control can see the arrow keys:

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);
}

Compile. Drop the new control from the top of the toolbox onto your form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜