当我有一个按钮时,C#keydown无法正常工作 [英] C# keydown not working when I have a button

查看:74
本文介绍了当我有一个按钮时,C#keydown无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上看到了问题,解决方案是将KeyPreview设置为true。我试过了,它仍然没有用。为什么当我按下其中一个箭头(向下,向上,向左或向右)时,标签仍然没有显示?



更新:

谢谢你的回答Peter Vegter,但它仍然不起作用。

为了清楚说明:常规字母确实工作并使标签显示出来。问题是箭头(向下,向上,向左或向右)不能工作。

我想我知道为什么 - 焦点在按钮上而不是在表格上。

我在网上搜索过这个,我发现我需要将KeyPreview设置为true。我做了它,当我按下箭头时,它仍然没有显示标签,只有当我按下字母时。

如果我删除按钮,箭头工作。



我尝试了什么:



I saw in the internet the problem, and the solution was setting the "KeyPreview" to "true". I have tried it, and it still didn't work. Why when I press one of the arrows (down, up, left or right) the lable still doesn't show off?

Updated:
Thank you for your answer Peter Vegter, but It still doesn't work.
To make this clear: regular letter does work and makes the label show off. The thing is that the arrows (down, up, left or right) don't work.
I think I know why - the "focus" is on the the button and not on the form.
I searched for this in the internet, and I found that I need to make the "KeyPreview" set as "true". I did it, and still it doesn't show the label when I press the arrows, only when I press letters.
If i remove the button, the arrows do work.

What I have tried:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            label1.Visible = false;
            this.KeyPreview = true;
            this.KeyDown += Form1_KeyDown;
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            label1.Visible = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }

推荐答案

您必须使用ProcessCmdKey来捕获箭头(和其他一些)键,如下所示:

You have to use ProcessCmdKey to 'catch' the arrow (and some other) keys, like this:
public Form1()
{
    InitializeComponent();
    label1.Visible = false;
}

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData)
    {
        case Keys.Left: // left arrow key
            label1.Visible = true;
            return true;

        case Keys.Right: // right arrow key
            label1.Visible = true;
            return true;

        // etc.
    }
    return base.ProcessCmdKey(ref msg, keyData);
}


这篇关于当我有一个按钮时,C#keydown无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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