通过箭头键单击防止按钮聚焦 [英] Prevent button from being focused by arrow key click

查看:30
本文介绍了通过箭头键单击防止按钮聚焦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户按下其中一个箭头键,如何防止表单上的按钮聚焦?
我正在编写一个小游戏,所以这会阻止用户移动.抱歉解释含糊不清.

How can I prevent that if the user presses one of the arrow keys, a button on the form is focused?
I am programming a small game, so this would prevent the user from being able to move. Sorry for the vague explanation.

播放器是一个 PictureBox,里面有一个可以移动的图形:

The player is a PictureBox with a graphic in it that is moved by:

private async void Form1_KeyDown(object sender, KeyEventArgs e)

推荐答案

处理这种情况的一种方法是设置 form.KeyPreview = true(请参阅 MSDN) 然后处理 KeyPress/KeyDown 事件处理程序:

A way to handle this scenario is to set form.KeyPreview = true (see MSDN) and then handle the keys in KeyPress / KeyDown event handlers:

为 KeyPress 事件引用 MSDN:

Quoting MSDN for KeyPress Event:

要仅在窗体级别处理键盘事件而不启用其他控件接收键盘事件,请设置表单 KeyPress 中的 KeyPressEventArgs.Handled 属性事件处理方法为 true.

To handle keyboard events only at the form level and not enable other controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event-handling method to true.

在您的 keysEvent 中测试箭头,按照您需要的方式管理它们并设置 Handled=true 以避免默认行为(将焦点移到下一个控件)

Test for arrow in your keysEvent, manage them the way you need and set Handled=true to avoid default behavior (move focus to next control)

这篇关于通过箭头键单击防止按钮聚焦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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