gpt4 book ai didi

c# - Move PictureBox using Arrow Keys - 处理 PictureBox 中的键盘事件

转载 作者:行者123 更新时间:2023-11-30 15:55:36 33 4
gpt4 key购买 nike

我有一个 PictureBox,我在其中使用下面的代码来移动我的对象。我需要在表单中添加一些按钮,但是当我启动程序时,箭头键在按钮之间导航,而不是我的输入按键。我试过很多Form.Load() 上的 PictureBox.Focus()PictureBox.Select() 之类的方法,并在此完全禁用箭头键导航回答here , 但我的对象将不再移动。

private void UpdateScreen(object sender, EventArgs e) {

if (Input.KeyPressed(Keys.Right) && Settings.direction != Direction.Left) {
Settings.direction = Direction.Right;
}
else if (Input.KeyPressed(Keys.Left) && Settings.direction != Direction.Right) {
Settings.direction = Direction.Left;
}
else if (Input.KeyPressed(Keys.Up) && Settings.direction != Direction.Down) {
Settings.direction = Direction.Up;
}
else if (Input.KeyPressed(Keys.Down) && Settings.direction != Direction.Up) {
Settings.direction = Direction.Down;
}
}

如何在不影响 UpdateScreen() 中的代码的情况下禁用所有按钮的箭头键导航?

最佳答案

PictureBox 控件不是Selectable,因此它无法处理键盘事件。要解决这个问题,首先应该使控件可选:

using System;
using System.Windows.Forms;
class SelectablePictureBox : PictureBox
{
public SelectablePictureBox()
{
SetStyle(ControlStyles.Selectable, true);
SetStyle(ControlStyles.UserMouse, true);
TabStop = true;
}

protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
this.Invalidate();
}
protected override void OnLeave(EventArgs e)
{
base.OnLeave(e);
this.Invalidate();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
if (this.Focused)
ControlPaint.DrawFocusRectangle(pe.Graphics, ClientRectangle);
}
}

然后你可以处理它的PreviewKeyDown事件:

private void selectablePictureBox1_PreviewKeyDown(object sender,
PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
e.IsInputKey = true;
myPictureBox1.Left -= 10;
}
else if (e.KeyCode == Keys.Right)
{
e.IsInputKey = true;
myPictureBox1.Left += 10;
}
}

关于c# - Move PictureBox using Arrow Keys - 处理 PictureBox 中的键盘事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48367078/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com