Why does my KeyPressEvent not work with Right/Left/Up/Down? - c#

In C#, I am trying to see if the user presses the right key so that a player moves right, but when I try it, it does not register the keypress:
private void KeyPressed(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == Convert.ToChar(Keys.Right))
{
MessageBox.Show("Right Key");
}
}
It does not display the MessageBox
This doesn't work for Left/Up/Down either
However, if I replace it with
if(e.KeyChar == Convert.ToChar(Keys.Space))
It works.
Am I doing something wrong?

You should use KeyDown event, e.g. for arrows:
private void KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
{
}
}
Arrow keys are not characters, so KeyPressed is not used for them.

Arrow Keys are in keyUp event they are:
Keys.Up, Keys.Down, Keys.Left, Keys.right
They are not triggered by KeyPressEventArgs.

Related

How to prevent call several KeyDown events by pressing a single key on the keyboard?

I have set KeyPreview property of the form to true in order to call keyboard events of the form before control events.
Both the form and the control in the form have KeyDown event like:
form:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)) {
MessageBox.Show("Control + Enter (Form)");
}
}
control:
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (!e.Control && (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)) {
MessageBox.Show("Control + Enter (TextBox)");
}
}
As you see the difference between these two parts of code is that in the form event code I need to call the KeyDown event when the user presses CTRL and Enter keys at the same time,
In the TextBox event code, I need to call the event when the user presses Enter key without holding CTRL-key.
The problem is that when I press Ctrl and Enter keys at the same time both of the above events will call.
How to prevent call both events?
I suggest you use the textBox1_KeyUp event. You can refer to the following code. My test was successful.
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return))
{
MessageBox.Show("Control + Enter (Form)");
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Control)
{
e.Handled = true;
}
else if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Control + Enter (TextBox)");
}
}
Use the ProcessCmdKey and like this.
protected override bool ProcessCmdKey(ref Message msg, System.Windows.Forms.Keys keyData)
{
int WM_ALRT_DOWN = 0x0104;
int WM_KEYDOWN = 0x0100;
if (msg.Msg == WM_ALRT_DOWN && (int)msg.WParam == (int)Keys.F4) //Alt + F4
{
return true; // The key is manually processed
}
if (msg.Msg == WM_KEYDOWN && (int)msg.WParam == (int)Keys.Escape) //Esc
{
return true; // The key is manually processed
}
if (msg.Msg == WM_KEYDOWN && (int)msg.WParam == (int)Keys.Space) //Space
{
return true; // The key is manually processed
}
}

My e.KeyCode == Keys.Add is writing in the textbox focused

I have this code in a windows form that calls a function that calculates a number:
private void KeyDown_Accion_Teclas(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add || e.KeyCode == Keys.Oemplus)
{
cmdAlta_Click(sender, e);
}
}
But in any textbox that is focused or selected, when I press the + button to call the function, its writes the symbol of +.
I only want to call the function but not to write the + symbol. Nothing I've tried has worked.
Any ideas?
private void KeyDown_Accion_Teclas(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add || e.KeyCode == Keys.Oemplus)
{
cmdAlta_Click(sender, e);
e.SuppressKeyPress = true;
}
}
Or maybe:
private void KeyDown_Accion_Teclas(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Add || e.KeyCode == Keys.Oemplus)
{
e.SuppressKeyPress = true;
cmdAlta_Click(sender, null);
}
}

C# Why is my control not accepting multiple keys in the KeyDown event

Ok guys so I've been working on this control for close to a month and one of the issues that I'm having is that if I press the CTRL key by it's self it registers and if I press the Space key by it's self it registers. I've tried to separate the two and I've tried to use them in the same if statement. Both are unsuccessful.
My first attempt was like this
protected override void OnKeyDown(KeyEventArgs e)
{
// base.OnKeyDown(e);
if (_isEditing)
{
if (e.KeyData == Keys.Delete)
{
if (_selectedObj != null)
{
DeleteSelectedObject();
}
}
}
if (e.Control && e.KeyData == Keys.Space)
{
_isEditing = !_isEditing;
Invalidate();
}
}
Now if I remove the Ctrl or the 'Space' key from the equation it works fine. So I tried to separate them and came up with
protected override void OnKeyDown(KeyEventArgs e)
{
// base.OnKeyDown(e);
if (_isEditing)
{
if (e.KeyData == Keys.Delete)
{
if (_selectedObj != null)
{
DeleteSelectedObject();
}
}
}
if (e.Control)
{
Console.WriteLine(DateTime.Now.ToShortTimeString());
if (e.KeyData.Equals(Keys.Space))
{
_isEditing = !_isEditing;
Console.WriteLine(DateTime.Now.Ticks.ToString());
}
Invalidate();
}
}
using the Console.WriteLine() as a cheater to tell me when the key is pressed and the Ticks doesn't get displayed unless I Comment out the CTRL clause. Where am I going wrong here?
Try something like
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Space)
{
}
You won't get modifier in a KeyDown event. Rather try one of the following ways to know if modifiers (Ctrl, Shift, Alt) are pressed or not:
Keyboard.IsKeyDown
if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
&& e.KeyData == Keys.Space){}
Check Keyboard.Modifiers
if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
&& e.KeyData == Keys.Space){}

How to capture Ctrl-Z keystroke in a RichTextBox

I need to capture when the user presses CTRL-Z (press CTRL and Z at the same time) in a RichTextBox control.
I've turned off the ShortCutsEnabled property. I've tried every combination I can think of using KeyCode and KeyData with the KeyDown and KeyPress events.
I can capture EITHER a CTRL OR a Z, but never both together. Is RichTextBox capturing this keystroke before I can see it, even if shortcuts are disabled?
Does anyone have a solution that works for this?
you could simply use CTRL-Z
textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Z && (e.Control)) {
MessageBox.Show("Ctrl + Z Pressed!");
}
}
Check KeyCode and Modifiers in the KeyDown event:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control && e.KeyCode == Keys.Z)
MessageBox.Show("Ctrl-Z Pressed");
}
void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((Control.ModifierKeys & Keys.Control) == Keys.Control && e.KeyCode == Keys.Z)
{
MessageBox.Show("Ctrl + Z is Pressed");
}
}
try this.

SplitContainer, how do stop cursor key input?

I want a c# split container that ignores cursor keys and can only be controlled with the mouse. How can I do this? This is so I can use the keyboard input in one of the side panels without simultaneously moving the split.
Using e.Handled = true or e.SuppressKeyPress = true to prevent the keys from resizing the splitter didn't work for me.
I was able to do it by setting IsSplitterFixed = true on KeyDown, and IsSplitterFixed = false on MouseDown/MouseMove (to allow resizing by mouse).
e.g.
public Form1()
{
InitializeComponent();
splitContainer1.MouseMove += splitContainer1_MouseMove;
splitContainer1.KeyDown += splitContainer1_KeyDown;
splitContainer1.MouseDown += splitContainer1_MouseDown;
}
void splitContainer1_MouseDown(object sender, MouseEventArgs e)
{
splitContainer1.IsSplitterFixed = false;
}
void splitContainer1_MouseMove(object sender, MouseEventArgs e)
{
splitContainer1.IsSplitterFixed = false;
}
void splitContainer1_KeyDown(object sender, KeyEventArgs e)
{
splitContainer1.IsSplitterFixed = true;
}
You may disable the keyboard input handling the KeyDown event of the control and if required, you may handle the event if the input matches specific keys.
Example
splitContainer1.KeyDown += new KeyEventHandler(splitContainer1_KeyDown); //Link the KeyDown event of splitContainer1 to splitContainer1_KeyDown
private void splitContainer1_KeyDown(object sender, KeyEventArgs e)
{
// if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right) //Continue if one of the arrow keys was pressed
// {
e.Handled = true; //Handle the event
// }
}
Moreover, you may stop the splitter from moving by canceling the SplitterMoving event of the SplitContainer control according to the KeyCode gathered from its KeyDown event
Example
Keys KeyCode; //This is the variable we will use to store the KeyCode gathered from the KeyDown event into. Then, check if it matches any of the arrow keys under SplitterMoving event canceling the movement if the result was true
splitContainer1.KeyDown += new KeyEventHandler(splitContainer1_KeyDown); //Link the KeyDown event of splitContainer1 to splitContainer1_KeyDown
splitContainer1.SplitterMoving += new SplitterCancelEventHandler(splitContainer1_SplitterMoving); //Link the SplitterMoving event of splitContainer1 to splitContainer1_SplitterMoving
private void splitContainer1_SplitterMoving(object sender, SplitterCancelEventArgs e)
{
if (KeyCode == Keys.Up || KeyCode == Keys.Down || KeyCode == Keys.Left || KeyCode == Keys.Right) //Continue if one of the arrow keys was pressed
{
KeyCode = Keys.A; //Reset the KeyCode
e.Cancel = true; //Cancel the splitter movement
}
}
private void splitContainer1_KeyDown(object sender, KeyEventArgs e)
{
KeyCode = e.KeyCode; //Set KeyCode to the KeyCode of the event
// e.Handled = true; //Handle the event
}
Thanks,
I hope you find this helpful :)

Categories

Resources