使图片框不会失去对箭头键的关注? [英] Make a PictureBox not lose focus on Arrow Keys?

查看:22
本文介绍了使图片框不会失去对箭头键的关注?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题 除了我想问如何让我的图片框不丢失专注于箭头键的按键.当我重载它并设置 TabStop = true 时它会获得焦点,但箭头键给我带来了问题.

This question except i want to ask how do i make my picturebox not lose 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.

推荐答案

这需要重写控件的 IsInputKey() 方法.需要相当多的额外手术才能让图片框首先获得焦点.首先向您的项目添加一个新类,使其看起来类似于:

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

这保证了控件可以得到焦点并且可以被tab键到.接下来,您必须撤消 TabStop 和 TabIndex 属性的属性,以便用户可以设置 Tab 键顺序:

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

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

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.

这篇关于使图片框不会失去对箭头键的关注?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆