如何在Form1上有一个按钮时触发KeyDown

时间:2017-05-22 05:01:43

标签: c# winforms

Form1窗口上存在一个按钮似乎可以防止触发KeyDown事件。我该怎么做才能使按钮不会阻止KeyDown被触发?

Here is a picture of my Form1. timer已启用。

代码:

    Brush brush;

    int dimensions;
    Point point;
    Size size;
    Rectangle rectangle;

    Color color;

    public Form1()
    {
        InitializeComponent();

        DefineRectangle();
        brush = Brushes.Black

        color = BackColor;
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.FillRectangle(brush, rectangle);
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Left)
            brush = Brushes.Green;
        if (e.KeyCode == Keys.Up)
            brush = Brushes.Yellow;
        if (e.KeyCode == Keys.Right)
            brush = Brushes.Orange;
        if (e.KeyCode == Keys.Down)
            brush = Brushes.Red;
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        DefineRectangle();
        Invalidate();
    }

    private void DefineRectangle()
    {
        Random random = new Random();

        dimensions = random.Next(5, 51) * 2;

        point = new Point
            (
                random.Next(284 / dimensions) * dimensions,
                random.Next(260 / dimensions) * dimensions
            );

        size = new Size(dimensions, dimensions);

        rectangle = new Rectangle(point, size);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        BackColor = Color.Blue;
        timer.Enabled = false;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        BackColor = color;
        timer.Enabled = true;
    }

2 个答案:

答案 0 :(得分:1)

在您的表单中,您可以尝试覆盖ProcessCmdKey:

protected override bool ProcessCmdKey(ref Message message, Keys keyData)
{
     if (keyData == Keys.Down)
          return true;

     return base.ProcessCmdKey(ref message, keyData);
}

在执行此方法之前,请为表单

设置KeyPreview property = true

答案 1 :(得分:1)

如果你想做一个简单的解决方法。只需将您指定的keydown处理程序添加到两个按钮的处理程序中。这应该可以使它工作,你可以继续做作业。

只需在设计器中选择它们,然后在属性菜单中将相同的方法绑定到它们的keyDown事件。

正确的解决方案是在构造函数

中执行此操作
    public Form1() : base()
    {        

        // Set KeyPreview object to true to allow the form to process 
        // the key before the control with focus processes it.
        this.KeyPreview = true;
}