[垃圾microsoft, 要啥缺啥] c# metro app keydown issue

下面这段代码是用来检测在textbox里 keydown event:

        private void txtTest_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            lblInfo.Text = lblInfo.Text + "," + (int)e.Key;
        }


尝试用keyboard reader来输入card content to textbox (以ENTER结尾),我原以为会把card info的字母or数字逐个显示在textbox里(以逗号隔开),但实际上只捕捉到最后的enter键,之前的key全部都捕捉不到。究其原因,原来和当前keyboard输入法有关!如果输入法是中文,虽然会在TEXTBOX里正确输出CARD INFO,但keydown event就只捕捉到enter键,如果输入法是英文,那么就可以捕捉到所有键。


和keyboard reader完全无关,因为你就算用virtual keyboard来在textbox里输入信息也是同样效果。


如果不是textbox,而是Controls.Page 来trigger keydown event, 因为对于中文输入法,textbox虽然捕捉不到keydown event,但可以通过获取textbox.text来获得card info。if use controls.page to trigger keydown event, then there must be at least one component in the page. passwordBox or button component is recommended (it looks that no chinese input issue for passwordbox and button), DON'T use textbox because of chinese input issue.

Note: if no component in the page is focused (for example, you tap any other area in the page), then it will not trigger any keydown event!!! Hence when the component lose focus, focus again.


Therefore, my solution of visitor log project smart reader view as below.

1. in the page, there is only one "cancel" button except 2 labels. When the button is clicked, back to parent page. If this button lose focus, focus again.

2. It seems that you needn't set this button focused explicitly, if it is only one component in page, it will be focused automatically when page is loaded.

### C# WinForms 中处理 KeyDown 事件 在 C# 的 Windows Forms 应用程序中,`KeyDown` 事件用于检测键盘按键操作。当特定键被按下时触发此事件。为了捕获并响应这些按键事件,在窗体或控件上订阅 `KeyDown` 事件,并实现相应的事件处理器。 下面是一个简单的例子来展示如何设置和使用 `KeyDown` 事件: ```csharp public partial class MainForm : Form { public MainForm() { InitializeComponent(); // 订阅 KeyDown 事件 this.KeyDown += new KeyEventHandler(MainForm_KeyDown); // 启用按键预览功能以便即使焦点不在当前窗口也能捕捉到按键消息 this.KeyPreview = true; } private void MainForm_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.C) // 检查是否按下了Ctrl+C组合键 { MessageBox.Show("Copy command detected!"); } else if(e.Alt && e.KeyCode == Keys.F4) // 检测Alt+F4关闭应用程序命令 { Application.Exit(); } Console.WriteLine($"Key pressed: {e.KeyCode}"); } } ``` 在这个实例里,通过重写构造函数中的初始化部分,订阅了表单级别的 `KeyDown` 事件[^1]。每当有按键动作发生时就会调用指定的方法 (`MainForm_KeyDown`) 来执行自定义逻辑。此外还启用了全局性的按键监听(`this.KeyPreview=true;`)使得即便其他子组件拥有输入焦点也可以接收到按键通知。 值得注意的是,对于某些特殊用途可能还需要考虑使用更底层的方式获取按键状态,比如利用Windows API 函数如 `GetAsyncKeyState()` 可以获得更加精确的控制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值