tags:

views:

23

answers:

1

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.

+2  A: 

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.

Hans Passant
Hey i notice when i right click i dont get the focus when i left click i do. Do you know how to make it so any click gets focus?
acidzombie24
That's normal behavior, try it with a button for example. You could override OnMouseDown and call this.Focus() to change it.
Hans Passant