2

我正在尝试使用 WinForms 和 C# 构建一个 Windows 应用程序,其中一种形式是我希望用户能够为每个动作分配键(即左、右、上、下运动等)。这类似于

在此处输入图像描述

在左侧列中将列出动作,用户应该能够为每个动作分配一个键。我对 Windows 窗体非常陌生,无法弄清楚要在左侧使用什么控件,我尝试使用带有 KeyDown 事件的按钮,但在此事件中不会触发输入/返回键,其余键它工作正常。那么应该使用什么控制以及什么事件,以便用户可以为任何运动/控制分配他选择的任何键。

编辑:这是最初的代码。

namespace ControllerWinServe
{


public partial class Form2 : Form
{
    static string[] array = new string[6]; 
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
    }
    private void button_d_Click(object sender, EventArgs e)
    {
    }
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
    }
    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
    }
    private void button_u_KeyDown(object sender, KeyEventArgs e)
    {
        MessageBox.Show("Form.KeyPress: '" + e.KeyCode.ToString() + "' pressed.");
    }

    private void button_d_KeyDown(object sender, KeyEventArgs e)
    {
        MessageBox.Show("Form.KeyPress: b2 '" +e.KeyCode.ToString() + "'pressed.");
    }
}
}

在尝试使用 user17753 的建议之后。

namespace ControllerWinServe
{
  public class EnterTextBox : TextBox
 {
  protected override bool IsInputKey(Keys key)
  {
    if (key == Keys.Enter)
        return true;
    return base.IsInputKey(key);
 }
}


public partial class Form2 : Form
{
    static string[] array = new string[6]; 
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
    }
    private void button_d_Click(object sender, EventArgs e)
    {
    }
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
    }
    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
    }
    private void button_u_KeyDown(object sender, KeyEventArgs e)
    {
        MessageBox.Show("Form.KeyPress: '" + e.KeyCode.ToString() + "' pressed.");
    }

    private void button_d_KeyDown(object sender, KeyEventArgs e)
    {
        MessageBox.Show("Form.KeyPress: b2 '" +e.KeyCode.ToString() + "'pressed.");
    }
}
}
4

1 回答 1

0

如果您说的是在 a 中按 enter,TextBox则默认情况下不会触发它。您可以创建一个名为 example 的新名称,EnterTextBox该名称派生自TextBox该覆盖IsInputKey以允许 enter 触发事件。

一种这样的实现可能是:

public class EnterTextBox : TextBox
{
    protected override bool IsInputKey(Keys key)
    {
        if (key == Keys.Enter)
            return true;
        return base.IsInputKey(key);
    }
}

使用项目命名空间中的此类,您将能够EnterTextBox从工具箱中添加项目命名空间类别下的内容。

然后您可以添加一个由KeyDown事件触发的方法,EnterTextBox例如:

    private void button1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            e.Handled = true;
            //stuff to do after enter is pressed
        }
    }
于 2012-10-03T20:16:04.220 回答