How to make keys call methods within C# program - c#

I'm new here, and I may be blasted for not seeing the old posts about Keys, but I assure you I have read many of them and cannot find the answer I am looking for.
I have a C# program, a calculator, that correctly calculates equations, but I want to be able to call methods by both clicking and keyboard input. Like so if user types in 2 + 2 ENTER the textbox will show 4. The only way the program does that at the moment is if the user actually clicks those buttons. Researching how Keys work in C# I found a lot of information about KeyCode and Keys, but very little information about how to actually implement them within the program. One thing that I came across concerning implementing the code was this:
private void Calculator_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
MessageBox.Show("Up button was pressed");
}
}
The name of the form is Calculator. I can compile this code without a problem, but it doesn't seem to do anything. I can place the entire program for you guys if you want, but it is several pages long and has a lot of comments and other stuff. I just don't understand why I can't make my program read a key. I also tried KeyPress instead of KeyDown, still nothing. Any help would be much appreciated.
Edit:
Marcel N. gave a good answer and I was able to get it to work after enabling the KeyPreview and using the code:
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.D1)
cmd1.PerformClick();
if (e.KeyCode == Keys.D2)
cmd2.PerformClick();
if (e.KeyCode == Keys.D3)
cmd3.PerformClick();
if (e.KeyCode == Keys.D4)
cmd4.PerformClick();
......................
}
I am very happy that all the numbers work, but am still having issues getting Enter, Divide, Multiply, and the arrow keys to work. Thanks for the speedy help.

You need to set the KeyPreview property on the form to true.
This will cause all key events to be passed to the form first, before they are delegated to the focused control. Then, you can use your current KeyDown handler to call your methods/handlers.
Finally, if you don't want the key events to reach the focused control at all then make sure to set the KeyPressEventArgs.Handled property to true when you receive the event at the form level.

Related

Can't escape from ToolStripTextBox in a particular case

It is hard to describe the issue. Let me illustrate it with a very simple example.
Start from a new solution of winform(.net framework 4.8).
Add a menustrip with a textbox, then a datagridview.
And let's handle KeyDown event of datagridview.
if (e.KeyCode == Keys.F3)
toolStripTextBox1.Focus();
Ok, now we start the program.
Click the datagridview to focus on it.
Click the textbox to change focus.
Press Esc on your keyboard.
You can see that the datagridview gets the focus as expected.
But if you make a little change in step two, the result will be confusing.​ Press F3 instead of clicking the textbox.​ When you press Esc this time, the focus is just lost.​ I tried to print the name and the handle of focused control. It turned out to be the textbox itself.​ Can somebody explain it?
Now I'm quite sure it is some kind of bug. After Jimi's mention of hwndThatLostFocus, I had traced this variable for several hours. Although I failed to locate the exact position where hwndThatLostFocus was changed, something unreasonable was found: when Focus() was called in different cases, the result lost consistency.
Under most circumstances, if Focus() of ToolStripTextBox is called, hwndThatLostFocus of ToolStripTextBox will be set to 0, just like the example in my question. But if you click the datagridview and click the ToolStripTextBox and then click the datagridview agian, this time you call Focus(), hwndThatLostFocus will remain a pointer to the datagridview. In addition, this could be reproduced in .net 6.
Later I will report this to Microsoft. For now, there are three ways to avoid this.
Simulate a mouse click by SetCursorPos and mouse_event in user32.dll.
Use reflection like Jimi's advice.
Override ProcessCmdKey in Form, and take care of Keys.Escape yourself:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape && msg.HWnd == toolStripTextBox1.TextBox.Handle)
{
dataGridView1.Focus();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
As I avoid using unnecessary reflect, and Dllimport is also some kind of ugly to me, I prefer the third one.

C#: KeyDown Event does not work in controls

I am trying to finish my final school project. I am creating a c# winform game to be specific. We can not use anything else.
I will not be posting here code because I got it pretty messed up and I guess u can answer me just with this info.
Setup:
I got my program set up like this. The is main form and two user controls. I switch those controls within the main form during the game. The first one is MENU and the second one is GUI with picturebox acting as a gamescene.
Problem:
Setup quite not important I guess. But what I need to do is to do some action when I press key Down on the first Control (while it is active in the form). Sounds easy I thought at first but the onKeyDown event in the menu.cs(1st usercontrol) is doing nothing when i press the key(The event method is not blank). I tried this.previewKey = true; in the menu load method but it did not even recognize it.
So my question is: Is there any way to use onKeyDown in usercontrols code?
I did it this way becouse I use the same keys in the second controls and i didnt want it to get messy (which obviously did the oposite huh)
TLDR: Need to use onKeyDown event in userControls (keyPreview might be the key)
BONUS
I also need to somehow link variables from Controls 1 to Form and Controls 2.
I looked it up and found out it would be easy in situacion like "Form to Form" but since it is userControls I cant figure it out and I feel like I am just a tiny bit from finishing it.(feels terrible sitting here 9 hours xD please help)
On the keypress event make sure it is for the selected control an not the main form. If you are capturing for the form to determine which key was pressed then use the keypress event for that. You can use a messagebox to verify that you have the right control. Every key has an integer value and you can access and use those by using the properties of e.
Bonus. Depending on how you implemented your code you will have to use either global varibles to pass the data across the forms or use delegates to actively access and set controls on another form
You have to register the event in the Form.Designer.cs :
private void InitializeComponent()
{
// Your form properties here
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
}
You're KeyDown event can be used like this in the Form.cs code :
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// To know if your event is working and the value of the key who's pressed
MessageBox.Show("Key Pressed = "
+ e.KeyCode.ToString()
+ ", Value = "
+ e.KeyValue.ToString());
// Example - add some actions bellow
if (e.KeyValue == 13)
MessageBox.Show("Return Key Pressed");
}

certain keys pressed event

im doing some work on a project that i need to pass my final exam.
So i choosed C#, Windows Forms, and i have something in my mind.
I need to help with event where i press keys on keyboard that represent word.
(like h-e-l-l-o) and if the keys will be pressed in this order something will happen, that i can figure out by myself, but i need help with the keypressed method or something.
TL;DR: I need help with event on my WinForm app that will work like when you type "AWESOME" to nowhere on youtube.
Here is some code from a project. Hook a function to the KeyPress event of the textfield. you can get the full contents inside the function or just the last pressed character.
private void IsKeyPressNumber(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (!(e.KeyChar >= '0' && e.KeyChar <= '9'))
e.Handled = true;
}
this.txtCode.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.IsKeyPressNumber);

C# WPF backspace event?

I'm new to WPF and C# so what I'm asking is if there is a backspace event like TextChanged event for TextBoxes?
I made a small Library program with renting books and everything is viewed at a ListView.
What I currently did is that you can filter book names just by typing inside the textbox, so if you have 1000 books and you type the letter 'b' then you might have only 150 books starting with 'b'.
The problem is whenever i press backspace, I want it to previously restore it to what it was.
For example: typing "bob" and then deleted b, I get bo and now i want to present what every starts with "bo".
Now I get the idea. All I need is just another textChanged event. but something need to inform that the text was changed, and I need something better then
if (backspace key is pressed) { Invoke textChanged }
Thx guys!
Well, should i delete the post? maybe some one else will search it someday.
backspace is actually causing a TextChanged event automatically! damn. thx anyway!
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx
Here is a reference on the msdn site.
http://csharp.net-informations.com/gui/key-press-cs.htm
On a different site (easier to read) This though looks like it is for Win Forms.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
MessageBox.Show("Enter key pressed");
}
if (e.KeyChar == 13)
{
MessageBox.Show("Enter key pressed");
}
}
Looks like you need to create an event that fires on a key down, then get the value of that key. I think there is a Keys.Backspace but to know for sure let intellisense help you.

Disabling F10 key from moving focus to menu bar in C# Winforms program

When I press F10 in my program, the focus is lost from my main program window, and moves to the menu bar. It turns out this strange behavior is common across many Windows apps.
I think it's ugly because the Alt key does the same thing, and we lose a precious function key. Why is Windows doing this, and how can I solve the case for my C# app?
Use the KeyDown Event for your form, and handle the Keystroke:
private void form_KeyDown(object sender, KeyEventArgs e)
{ if(e.KeyData == Keys.F10)
{
// Do what you want with the F10 key
e.SuppressKeyPress = true;
}
}
Also make sure that your forms KeyPreview is set to true.
this might solve it for you
http://geekswithblogs.net/aghausman/archive/2009/04/26/disable-special-keys-in-win-app-c.aspx
i used below trick:
SendKeys.Send("Alt");
this code relieve the form from F10 key.

Categories

Resources