Antmoritz
Antmoritz

Reputation: 11

Focus picturebox when entering form

I am creating a simple game for school in C#, where I am controlling a character using the WASD keys. The character is taken from a sprite sheet and put into an imagelist. The imagelist is in a picturebox.

Everything works fine when it's just the picturebox in the form, but when I add a button or something else, it's like it lose focus. It doesn't respond.

I have searched endless pages for a solution to set focus on the picturebox when the form opens, but I haven't found anything that works.

I would really appreciate some help.

Edit: It's WinForms.

Upvotes: 1

Views: 2942

Answers (2)

Freakyd
Freakyd

Reputation: 11

I found event MouseHover with pictureBox1_Hover calling pictureBox1.Focus() worked. When the mouse was hovered over the PictureBox in question, it would gain focus. Other than that, it didn't seem that calling pictureBox1.Focus() during form load had any effect on the focus.

this.pictureBox1.MouseHover += new System.EventHandler(this.pictureBox1_Hover);
private void pictureBox1_Hover(object sender, EventArgs e)
        {
            pictureBox1.Focus();
        }

It worked for me!

Upvotes: 1

Phil Wright
Phil Wright

Reputation: 22906

The PictureBox cannot take the focus. It is intended as a way to show an image but not intended to allow user input such as via the keyboard.

A crude approach would be to intercept the OnKeyDown event on the Form itself and then test for the keys of interest. This will work as long as the control that has the focus, such as your Button, does not want to process those keys itself.

A better approach would be to override ProcessCmdKey() method of the Form. This method is called on the target control, such as your Button, to decide if the key is special. If the Button does not recognize it as special then it calls the parent control. In this way your Form level method will be called for each key press that is not a special key for the actual target. This allows the Button to still process a ENTER key which is used to press the Button but other keys will be processed by your Form.

Lastly, to intercept all keys before they are handled by any of the controls on the Form you would need to implement the IMessageFilter interface. Something like this...

public partial class MyWindow : Form, IMessageFilter
{
    public MyWindow()
    {
        InitializeComponent();
        Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m)
    {
        // WM_KEYDOWN
        if (m.Msg == 0x0100)
        {
            // Extract the keys being pressed
            Keys keys = ((Keys)((int)m.WParam.ToInt64()));

            // Test for the A key....
            if (keys == Keys.A)
            {
                return true; // Prevent message reaching destination
            }
        }
    }

    return false;
}

Upvotes: 2

Related Questions