How to react on (+,-,*/) in my calculator - c#

In c# I am using this code to imediately react on press keys.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.NumPad1)
{
button_1.PerformClick();
return true;
}
}
I defined this for all numpad numbers and it WORKS great. But I am not able to define this function for (/,,-,+) on NumPad. I have read some topics with solution throw keyCode...it was like if(e.keykode==46) than something. But it worked after i pressed enter. I need imediatly reaction no keys +,-,,/. Can somebody help me pls?

You're looking for Keys.Add, Keys.Divide, Keys.Multiply, and Keys.Subtract, I believe.
To use them, that would be exactly the same as you have already done:
if(keyData == Keys.Multiply) { // or Add, Divide, or Subtract
btnMultiply.PerformClick(); // Or whatever else you want to do here.
}

Do you want this to occur in an event like so:
private void txtText_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add)
{
//do something
}
}
Something like this should work for you.

Related

C# Cannot handle Ctrl+K event of textbox

I would like to perform some actions when the user presses Ctrl + K on a textbox.
private void subject_TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.K)
MessageBox.Show("!");
}
Nothing happens when I run it.
When I debug I can see that e.Control is true (this means I pressed Ctrl) but the e.KeyCode is not equivalent to K.
Any ideas?
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.K) && focusedTextbox == subject_TextBox)
{
//Some Code
}
}
private TextBox focusedTextbox = null;
private void subject_TextBox_KeyDown(object sender, KeyEventArgs e)
{
MethodName(e.KeyCode)
}
private void MethodName(Keys keys)
{
focusedTextbox = (TextBox)sender;
}
Use this code, this should work i have tested it myself and it will work, you will want to run the 'MethodName' method in each textbox, or if you can find a better way to change the 'focusedTextBox' field then do that hope this helped.
In the KeyDown event, you just ask for the 'state' of the keyboard.
You might want to check out this topic:
Capture multiple key downs in C#
Really don't know what is the problem reason.
May the event is fired as soon as the Ctrl is pressed, without waiting to the K to be pressed as well.
However, when I use the same code in the TextBox_KeyUp event, it works fine.

How do I bind a keyboard key to a label

I am trying to bind a keyboard button (preferably "ESC") to stop the code that is running inside the method. But the thing is, it only works with actual buttons, is there anyway to bypass this so it works when pressing labels aswell?
private void label1_Click(object sender, EventArgs e)
{
if (e.Control && e.KeyCode.ToString() == "ESC")
{
MessageBox.Show("This does now work");
}
}
I've read somewhere that it is possible its just that the Visual Studio GUi doesnt provide it, but you can do it with code somehow, is this true?
I am not sure what you are trying to do. The following will get the Escape key when it is pressed when the focus is in the form regardless of what control has the focus. Just add this to the form (the code of course).
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Escape))
{
MessageBox.Show("This works");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}

Disable all key functions of a ListBox

I have a listbox in one of my user controls, and if certain keys are pressed it acts accordingly. My problem is that there are already some keys that do specific functions for the listbox (eg. arrows move up and down, dynamic search etc.). What I need is to disable all of these and handle the listbox on my own. Any way I could achieve this?
Inside the Form or UserControl where you have the listbox specified add this code:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (msg.HWnd == yourListBox.Handle)
{
//Check the keyData and do your custom processing
return true;//Say that you processed the key.
}
return base.ProcessCmdKey(ref msg, keyData);
}
If you want to disable all keys on your ListBox, you can use the following code
private void Listbox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
e.Handled = true;
}
You can accept some especial keys if you want as well. For example if you want to accept just the Enter key
private void ListBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
If e.Keycode==keys.Enter
{
//do what you want
}
Else
{
e.Handled = true;
}
}

C# KeyPress event method not registering with visual studio? Or code?

when running my game (snake) I am suppose to be able to move the snake around the form using the keys w,a,s and d. (atm I have only written the code for left and right movement just has a jumping off point). However, when running the program nothing happens. I have tried using break points, however, it seems as if my program isn't even reading the keypress method, even though I am pressing keys.
Here is the Move method in the snake class.
public void Move(int pixels)
{
if (pixels < 0)
{
xPosition_ = xPosition_ -= SNAKE_WIDTH;
}
else if (pixels > 0)
{
xPosition_ = xPosition_ += SNAKE_WIDTH;
}
}
And here is the keypress method.
private void GameScreen_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 'a')
{
snake.Move(-1);
}
if (e.KeyChar == 'd')
{
snake.Move(1);
}
this.Refresh();
}
the graphics get drawn fine to the pictureBox control.
Thanks in advance.
One possible problem is that your event handler isn't actually connected to the KeyPress event. You need to wire up the KeyPress event to your event handler in order to make it work; simply naming it GameScreen_KeyPress isn't enough. For example, here's how you could do this in the constructor of GameScreen:
public void GameScreen()
{
this.KeyPress += new EventHandler(GameScreen_KeyPress);
}
Here's an MSDN article on the subject: How to Consume Events in a Windows Forms Application.
The best way of doing this is to override ProcesCmdKey for your form, like the example below:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
MessageBox.Show("Pressed: " + keyData);
return base.ProcessCmdKey(ref msg, keyData);
}
Do you have the KeyPreview set to true on the form?

How to Stop Window Error Sound When Typing 'Enter' or 'Esc'

I have a form with a single text box on it. No other controls. Whenever I type the 'Enter' key or the 'Esc' key, the form functions as I desire; but I hear that horrible Windows error sound. The code looks similar to the following...
public class EntryForm: Form
{
public EntryForm()
{
}
private void EntryTextBox_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
// do some stuff
Hide(); // I've also used DialogResult = DialogResult.OK here
e.Handled = true;
}
else if(e.KeyCode == Keys.Escape)
{
Hide(); // I've also used DialogResult = DialogResult.Cancel here
e.Handled = true;
}
}
}
I can 'hack' it and make the noise stop by adding the following code to the form's constructor.
AcceptButton = new Button();
CancelButton = new Button();
As I stated this causes the sound to not play, but I think this is bad form; especially since I don't need a button on the form.
Anyone know why this is the behavior and if there is a cleaner way to stop the error sound from playing?
In the KeyDown event, set e.Handled = true and e.SuppressKeyPress = true.
There's a more "correct" fix, one that works regardless of how many controls you have and follows the Windows Forms design model. Paste this code into your form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Escape || keyData == Keys.Enter) {
this.Hide();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
This is too long a reply to Nobugz answer to fit in a comment. If you use Nobugz code as is :
the Form is going to be hidden no matter which control on the form is active and has keyboard input focus, and that is independent of whether the Form has the 'KeyPreview property set to 'true or 'false.
Here's what you need to do to make only a specific control (in this case a TextBox named 'textBox1) be hidden in the ProcessCmdKeys over-ride :
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (msg.HWnd == textBox1.Handle)
{
if (keyData == Keys.Escape || keyData == Keys.Enter)
{
textBox1.Hide();
return true;
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
Of course if you wanted to handle the case of multiple controls needing to be hidden, you could implement a 'switch statement or whatever to test the msg.HWnd against : note I make the assumption here that all controls that could have keyboard input will have a valid HWnd.
Some memory (vague) of a situation in which I used this technique, and a text input control somehow still had keyboard input focus ... when I did not intend for it to ... makes me want to add an additional test like this :
&& this.ActiveControl == textBox1
But, take that with a "grain of salt" since I can't be certain it is necessary.

Categories