KeyDown/KeyPress简单问题. [英] KeyDown / KeyPress Simple question.

查看:84
本文介绍了KeyDown/KeyPress简单问题.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这两个示例是否有效.我一直在为一个学校项目做一些研究.我想调用一个在按下/按下键时不需要执行任何操作的方法(例如,将文本添加到textBox1 ..)(不需要按回车键.)我希望它非常简单,但是我不明白如何触发它们以及它们是否正确编写.任何帮助的尝试都将不胜感激.谢谢你.

I don''t know if these two example work. I''ve been doing some research for a school project. I want to call a method that does something (for example adds text to textBox1.. ) when the key is pressed/down (without the need of hitting enter.) I want it to be very simple, yet I don''t understand how to trigger them and if they are written correctly. Any attempt to help is very appreciated. Thank you.

//Keypress:
private void myControl_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.a)
{
// call method?
}
}

//Keydown:
 private void Grid1_KeyDown(object sender, KeyEventArgs e)
        {
                if (e.KeyCode == Keys.a)
                {
                  //call method?
                }
        }

推荐答案

请记住,它们只有在您控制焦点时才会触发:我假设您已将它们设置为事件的处理程序,是在设计器的控件属性"窗口中,还是通过在Load事件表单中手动添加它们?

开始只是为了进行测试:

创建一个新窗体并处理KeyPress,KeyUp和KeyDown事件.在每个窗口中,添加一个Console.WriteLine语句以标识您所在的位置.(运行程序时,您可以在屏幕底部的输出"窗格中看到此输出.

玩弄代码,直到确定发生了什么,然后将代码转移到您真正感兴趣的控件上-只需记住焦点即可!
Bear in mind that they will only trigger when you control has the focus: I assume you have set these as the handler for the event, either in the control Properties window of the designer, or by manually adding them in the form Load event?

Start simply for testing:

Create a new form and handle the KeyPress, KeyUp and KeyDown events. In each of them, add a Console.WriteLine statement that identifies which you are in. (when you run you program, you can see this output in the Output pane at teh bottom of the screen.

Play with the code, until you are sure what is happening, and then transfer the code to the controls you are really interested in - just remember the focus!




例如,如果您使用文本框,则第一种方法是正确的.只需将事件处理程序以load
的形式添加
this.textBox1.KeyPress + =新的System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);

您可以对所有支持按键事件的控件执行此操作
Hi,

For example if you are using a text box your first method is correct. Just need to add the event handler in the form load

this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);

You can do this for all the controls which supports keypress event


您始终可以使用SendKeys ^ ]来触发您自己的键盘事件.
You can always use the SendKeys method [^]to trigger keyboard events of your own.


这篇关于KeyDown/KeyPress简单问题.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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