输入表单时聚焦图片框 [英] Focus picturebox when entering form

查看:54
本文介绍了输入表单时聚焦图片框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C# 为学校创建一个简单的游戏,我在其中使用 WASD 键控制一个角色.角色从精灵表中取出并放入图像列表中.图像列表位于图片框中.

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.

我非常感谢您的帮助.

它是 WinForms.

It's WinForms.

推荐答案

PictureBox 无法获得焦点.它旨在作为一种显示图像的方式,但不允许用户通过键盘进行输入.

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.

一种粗略的方法是拦截 Form 本身的 OnKeyDown 事件,然后测试感兴趣的键.只要具有焦点的控件(例如您的 Button)不想自己处理这些键,这就会起作用.

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.

更好的方法是覆盖表单的 ProcessCmdKey() 方法.在目标控件上调用此方法,例如您的 Button,以确定键是否特殊.如果 Button 没有将其识别为特殊的,则它会调用父控件.通过这种方式,您的 Form 级别方法将针对每个不是实际目标的特殊键的按键调用.这允许 Button 仍然处理用于按下 Button 的 ENTER 键,但其他键将由您的表单处理.

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.

最后,要在表单上的任何控件处理所有键之前拦截所有键,您需要实现 IMessageFilter 接口.这样的事情...

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

这篇关于输入表单时聚焦图片框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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