How to implement the keyboard key press in Windows Form Application

瘦欲@ 提交于 2021-02-10 22:30:25

问题


I want to implement the keyboard button press commands inside a c# windows form application. Suppose if some value is reached I want to implement the key "L" pressed using the windows form application.Is this possible ? How to do it ?


回答1:


This might do the trick for you

However, a better way is probably to set your form's KeyPreview property to true, and then put your code into the form's keyDown event (and set e.Handled = true as well, to prevent the key event from being passed on to whichever control does have the focus).

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.L)
     {
        //Do here
     }
}

You would also like to view MSDN: Handle Keyboard Input at the Form Level which states about Windows Forms provides the ability to handle keyboard messages at the form level, before the messages reach a control.

Edit

WM_KEYDOWN: This message is posted to the window with the keyboard focus when a nonsystem key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.

SendKeys: Use SendKeys to send keystrokes and keystroke combinations to the active application. This class cannot be instantiated. To send a keystroke to a class and immediately continue with the flow of your program, use Send. To wait for any processes started by the keystroke, use SendWait.

so when you receive signal from any device

System.Windows.Forms.SendKeys.Send("S");

and on keyDown

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyCode == Keys.S)
     {
        //Shooting Code
     }
     else if (e.KeyCode == Keys.L)
     {
        //Some Other Code
     }
}

and apart from that Programmatically generate keypress events in C#? will also give you an idea to implement your task




回答2:


Actually what happends is I receive some data to the Windows Form application via bluetooth from a Arduino and some sensors connected remotely. According to those data I have a game Developed using "construct2" which I need to control. The game users keyboard keys to control it.

In the game when Key "S" is pressed it shoots the targets, when another key pressed it does something else. So what I basically need to do is to implement the keyboard key press according to the signals received in the Windows form applications. Please let me know if this is possible ? I do not need to identify the key press events from within but I need to implemet the key press from within the application



来源:https://stackoverflow.com/questions/33818896/how-to-implement-the-keyboard-key-press-in-windows-form-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!