从键盘检测按键并激活事件 [英] Detect Key Press from keyboard and activate the event

查看:115
本文介绍了从键盘检测按键并激活事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友,

我已经用C#准备了一个计算器.一切正常,但是我想做一些新的事情,即当用户从键盘上按下某个键时,与之相关的事件应该被激活.例如:如果用户从数字小键盘上按数字1,则文本框中的值应为1并且值1出现,但是再次应激活文本框;如果用户按键盘上的加号,则应激活添加按钮单击事件,但是实际发生的是+符号出现在文本框中,这不应该发生.

每次用户按下键盘上的任何键时,控件都应转移到文本框.请任何人都可以帮忙吗?

在此先感谢!!!

Dear Friends,

I have prepared a calculator in C#. Every thing is working fine, but I want to do something new i.e. when the user press a key from keyboard the event related to it should get activated. for eg: if user presses number 1 from numerical keypad then in textbox value should be 1 and the value 1 comes but then again textbox should be activated and if the user press plus key on keyboard then the add button click event should get activated, but what actually happens is that + sign appears in textbox, this should not happen.

Every time the user presses any key on the keyboard, the control should get transfered to the textbox. Please Can Anybody help ???

Thanks in Advance !!!

推荐答案

我假设您有WinForms应用程序?我甚至可能会使用OnKeyPress做您想要的事情,但是OnKeyUpOnKeyDown事件对于您的特定情况可能更好.
I assume you are have a WinForms application? I would likely use the OnKeyPress even to do what you want, but the OnKeyUp or OnKeyDown events might be better for your specific case.


好,因此解决方案1可以处理按键,只要在文本框中不显示加号,您就需要在KeyDown或KeyUp事件处理程序中执行以下操作:

Ok so Solution 1 handles the key press and as far as not displaying the plus sign in the text box you will need to do something like this in your KeyDown or KeyUp event handler:

if (e.KeyCode == Keys.Add || e.KeyCode == Keys.Oemplus)
{
    //do not add this to the text box
}


以上两个答案都是正确的.但是,我想向您指出一些我经常忽视自己的细节.当您希望Form升高KeyDownKeyUpKeyPress Events时,应确保 ^ ]设置为true.然后,您的Form将获得您进行的所有按键操作(以及您在Form中的Controls中进行的按键操作).
您可能感兴趣的另一种阅读方法是如何完成编程 [
The two above answers are both correct. However, I would like to point you on a little detail that I have often overlooked myself. When you want your Form to raise the KeyDown, KeyUp, KeyPress Events you should make sure the KeyPreview Property[^] of your Form is set to true. Your Form will then get ALL key presses you make (also key presses you make in Controls on your Form).
Another read you might be interested in is How Programming Should Be Done[^] by Marc Clifton. Compare it to your own calculator and see where your two are different. Could be a great way to see how things could be done differently :)


这篇关于从键盘检测按键并激活事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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