How to perform functions on keyboard press c# - c#

I'm relatively new to C# and I want to know how can I press a key on my keyboard say the Q key and have it preform a list of functions?
I want to form a list of function under neath it. Anybody have any idea how to do this? thanks
//Something like this
if keyboard_down(Q)
{
//Do events here
}
I know this isn't the right function but that is basically what i want it to do. Winforms

You didn't mention which technology you work with.
I will assume that you are using Winforms.
In order to react to Key Press event you need to use Control.OnKeyPress - See here
See also this example which shows how to handle 'enter' key press

Depends on the way you want it.
Do you want them to fire while the form got focus or even without any focus to the form?
With focus:
Click your form in the form-designer and then go to the properties-tab. Click that little lightning bolt on top of it. There are a lot of events in that list. Double click "Keypress" and it will create an event automaticly and open the right code-snipped for you.
Depending on the focus you want, you can also mark controlls inside the form designer and then create the keypress event.
Without focus:
This would be a bit more difficultly. Here you would need to use a global keyboard hook to permanently grab pressed keys. Google for "c# keyboard hook". There are some examples out there.

Related

How to set focus back to form, after button is pressed

I am making a game, and to open up and close the store, you press S. While in the store, you have six different choices to buy from, but they are all buttons.
However, once you buy something, the focus is no longer on the form, but on the button, and the key down event is part of the form, therefore, because the focus gets switched from the form to the button, the key down event no longer works, and disables you from closing the store and continuing on with the game.
My question is how to set the focus back to a form once a button is press? I started out with visual basic, and the code would be something along the lines of form1.setfocus, but its totally different in c#.
I have tried Activating the form, .focus, a lot, and nothing seems to be setting the focus back to the form. Help would be greatly appreciated.
Form1.focus();
But I think, to get keyboard events on Form itself, you need KeyPreview set to true for the Form so that Form gets Keys first and then other controls.
Try:
form.Focus();
MSDN:
The Focus method returns true if the control successfully received input focus. The control can have the input focus while not displaying any visual cues of having the focus. This behavior is primarily observed by the nonselectable controls listed below, or any controls derived from them.
Tell me more
You can add the key down event to the buttons too.

How do I know when a button is released?

So I'm making a simple program where I need to know if a button is pressed, and I need to know when a button is released after it's been released. I need to be able to complete an action when it's released
Winforms/WPF: MouseUp
WebForms: onkeyup
It's not really clear if you're working with webforms or winforms, but .NET provides event handlers for pretty much any event that could happen.
Here's a listing of the events Buttons handle.
The one you're looking for is 'Click'. This method will be fired whenever the user clicks on the button.
If you need to do something when the user pushes down on the mouse and again when he releases, Button isn't right for you. Many other objects implement the 'OnMouseDown' and 'OnMouseUp' events, though.
If you're talking about a winform and a keyboard press use the KeyUp event ( http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keyup.aspx ) If you're talking about a mouse click use MouseUp ( http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mouseup(v=vs.71).aspx ).

Problems with the KeyPress, KeyDown and KeyUp events in C#

So how to begin.
I am asking when you make a game for example and you add a controlls how do I make the form's key events run when the focus isnt on the form but on some of the controlls and when i call this.Focus() or this.Select() it doesnt't happen anything, but if I use a empty form(with no controls) it works(the events respond).And when i have for example 2 buttons and call button1.focus() and press a key the button1's event handler responds (only it) adn then when i call button2.Focus() it responds for button2.How is focus distributed througt the controlls?
I know for muttons you have to click them once to put the focus on them automaticly and for textboxtes too,but when i click the form it doesnt move the focus on the form.
Im have almost no experience with Key events please explayn me how to use them and how they function understandly.
PS: sorry for the long questin
You can set the Form.KeyPreview to true to have the form react to key events.

Always handle the PreviewKeyDown event in a base form

We need to handle this event in the base form, regardless of which controls currently have focus. We have a couple of global key commands that need to work regardless of control focus.
This works by handling the PreviewKeyDown event in the form normally. When we add a user control to the form, the event no longer fires.
Am I missing something trivial here? Or do we need to handle the event in the user control first?
Thanks for your help!
Thanks Factor. When I get more time :) I'll get it working 'properley'!
The hidden menu you are using works fine for shortcuts that are valid menu item shortcuts, but if you want to use any key as a shortcut (such as Page Up/Page Down), you'll need a different trick.
Another way to do this that doesn't involve P/Invoke is to set the Form.KeyPreview property of your form to true. This will cause all key presses to be sent to the form first, regardless of which control has focus. You can then override OnKeyDown, OnKeyPress, and/or OnKeyUp to handle the key press before any of your controls.
This is probably not the best way of doing it, but the first way that comes to mind.
In your forms constructor, after you call InitializeComponent(); do something like this:
foreach (Control control in this.Controls)
{
control.PreviewKeyDown += new PreviewKeyDownEventHandler(HandlePreviewKeyDown);
}
I THINK that should do the trick. In your HandlePreviewKeyDown method you can then do your work and it should trigger regardless of which control has focus.
PreviewKeyDown only works when the control has focus. It sounds like you should look into an application level hook for a special shortcut keys. You'll have to do it with a P/Invoke. SetWindowsHookEx on pinvoke.net is a good place for an example. Here's a MS KB article about a mouse hook in c#, which appears to be expanded to a keyboard hook in this article.
We ended up doing this:
I found a workaround for this by setting up a hidden menu item by setting:
ToolStripMenuItem.Visible = false
(Thanks to this article).
It appears that the Main Menu of a form always gets searched for your shortcut key combination. This works regardless of whick control has focus

In .Net, what's the better choice to code key presses in keyboard, key-up or keydown?

Are the two events the same or are there differences that we should take note when coding the keyboard presses?
My answer here is just based on experimenting with different applications, not programming per se.
Handle the keydown. Let that be the trigger for your logic. That's what the user would expect based on interacting with other applications.
For example, try a key down in Notepad, and you'll see that the DOWN triggers the reaction in Notepad. It doesn't wait for the UP.
It doesn't matter if it's .Net or not, it matters what the user expects. Keydown is a good time to respond to the four arrow keys. Character input is a good time to respond to input of visible characters. Keyup is usually a good time to respond to any action that is going to have an effect on a document, but keydown would be better if it's a game where the user wants immediate effect.
It's not really "which is a better choice for .NET."
You really have to think about how you want to respond to key presses. If you want to what someone is typing in a text box it's usually best to wait until they've released before trying to decide what they're doing. But if it's something like a game where you want to respond the instant it's pressed, than you would use KeyDown.
KeyDown is the moment the key is pushed down.
KeyUp is after the key has been released.
One thing to consider that I've had a problem with before:
If you handle something on key down that changes the window or changes UI component focus, then the new UI element may sometimes get the key up event.
This happened to me at my last job. We had a control on a form that, on key down, would load a new form. If the new form loaded fast enough, then the new form would get focus before the user released the key, and the new form would get the key up event. We had a UI control on that 2nd form that reacted to key up, and it would sometimes get triggered unintentionally.
The moral of the story is; keep it consistent. Pick one or the other and stick to it :)
The key down event happens as soon as the user presses a key, the key up event happens when they release the key after pressing it.
So if you use the key up event, and the user presses a key and holds it for 5 seconds, nothing will happen until they let go of it.
(Note: I know nothing about .net, I've just used 'key up' and 'key down' events in other libraries.)
I allmost allways use KeyDown, because then I can use e.Handled=True and stop the keyevent to travel from textbox to container and down in the eventque if I want. You can use e.Handled in KeyUp also, but then its "to late" because the key the user entered will be seen in the textbox and you have to take it away manually if you for example want to stop the user to enter digits in the textbox.
Another thing to take into account: When holding modifiers, it's important to use keydown. I generally use keydown to set a variable like ctrlPressed=true; then use keyup to unset that variable ctrlPressed=false;
I generally use keyPressed for all alphanumeric characters.
This sort of system allows you to enable things like CTRL+K+C ala Visual Studio

Categories