Detect Shift+1 as Key.Add - c#

I would like to detect the user pressing the "add" key in the .net 4 WPF KeyDown event handler. To do this I use the following test:
if (e.Key == Key.Add)
This doesn't detect the case when the user presses Shift+1 (which corresponds to "add" on my keyboard layout).
How can I detect this? I'm not convinced that testing
if (e.Key == Key.D1 && Keyboard.Modifiers == ModifierKeys.Shift)
is the right solution as it may be mapped elsewhere on another keyboard layout.
Any suggestions?

You might consider using the KeyPress event handler instead.

private void trackBarFrames_KeyDown(object sender, KeyEventArgs e)
{
switch ( e.KeyCode)
{
case Keys.Add :
// Nummeric Keypad Add
AddSomething();
break;
case Keys.Oemplus :
// Regular keyboard Add
// OemPlus is assigned to the regular keyboard key with a "Add" Sign but doesn not take shift conditions in account..!
if (e.Modifiers == Keys.Shift)
{
AddSomething();
}
break;
}
}

Related

Forms, basic calculator key triggering problem

private void UserInputText_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.D4 && e.Modifiers == Keys.Shift) || (e.KeyCode == Keys.Add))
{
if (String.IsNullOrEmpty(UserInputText.Text))
{
MessageBox.Show("Bir sayı giriniz.");
UserInputText.Clear();
return;
}
if (double.TryParse(UserInputText.Text, out sayı1))
{
CalculationResultText.Text = sayı1 + " + ";
islem = "+";
UserInputText.Clear();
}
else
{
MessageBox.Show("Sadece sayı değeri girebilirsiniz.");
UserInputText.Clear();
}
}
}
I am coding a basic forms calculator. I am trying to trigger addition function and clear the textbox when textbox is focused and user presses "+" key. "if (String.IsNullOrEmpty(UserInputText.Text)) and else conditions work well. But if no Message boxes shows up as in the
if (double.TryParse(UserInputText.Text, out sayı1)) condition, the "+" character remains in the textbox as in the image. Thanks for help.
If I understand correctly, you want to first check the character that was typed in and if it's incorrect then you want to prevent this character from appearing?
If so, then you need to set e.Handled = true property when you want to prevent it.
This call tells the GUI element (your TextBox) that "I did all the checks for this event (i.e. KeyDown event), and I don't want you to contribute in handling of this event (i.e. normally the TextBox would try to add this character to its Text property, but you prevent it)".
Check out documentation on KeyEventArgs.Handled.
KeyPress event enables you to prevent any further changes in the TextBox.
You can do that thanks to Handled property of KeyPressEventArgs
private void UserInputText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '+')
{
UserInputText.Clear();
e.Handled = true;
}
}

How I can capture multiple keys?

I need to capture multiple keys in the same time like "Shift+Insert" how I can use this using System.Windows.Input.KeyEventArgs. I've written some code but it doesn't work:
private void Grid1KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Shift && e.Key == System.Windows.Input.Key.Insert)
{
//do something
}
}
Could anyone help me?
Note: In silverlight project you are not allowed to use "System.Windows.Forms".
Rather try something like
if (e.Shift && e.Key == System.Windows.Input.Key.Insert)
{
//do something
}
Have a look at KeyEventArgs Class
A KeyEventArgs, which specifies the key the user pressed and whether
any modifier keys (CTRL, ALT, and SHIFT) were pressed at the same
time, is passed with each KeyDown or KeyUp event.
You could also look at KeyEventArgs.Modifiers Property
Gets the modifier flags for a KeyDown or KeyUp event. The flags
indicate which combination of CTRL, SHIFT, and ALT keys was pressed.

C# Windows Forms :FrameWork 2.0 Multiple Keys Detection on UserControl

I want to Recognize Ctrl+E keys pressed on a TextBox which is inside a UserControl ,For this am using the textbox_KeyDown(object sender, KeyEventArgs e) event and checking for the following condition
if(e.KeyCode == Keys.E && Control.ModifierKeys == Keys.Control)
{
//Code
}
For some reason the first part of the if condition i.e (e.KeyCode == Keys.E) is returning false as e.keycode has Lbutton|ShifKey as its value.
1>Why is it not detecting the 'E' key press down ?
2>Should we handle this event diffrently as it as a UserConrol?
*Note:Above Code Worked fine if it is a normal Form.I also tried toggling the KeyPreview value of the form that hosts the userControl nothing seems to me working.
Can anybody please help me out on this.
Thanks in Advance
You are just getting confusing information from the debugger. The Keys enum has the [Flags] attribute but it doesn't actually use bits to identify keys consistently. LButton|ShiftKey == 0x01|0x10 == 0x11 = Keys.ControlKey. And that's expected since you hit the Ctrl key first. It is the next keystroke that you want, when you press E while holding down Ctrl. But that won't come because the debugger break messed that up.
The best way is:
if (e.KeyData == (Keys.E | Keys.Control)) {
// etc...
}
It should be:
if (((e.KeyCode & Keys.E) == Keys.E) && e.Control)

keydown to correspond with button down

Hello I am trying to match the button down visual (on the WinForm, the button boarder gets a little darker, indicating it is pressed) with a keydown event. First of all I need to detect a keydown for numbers only. Then when the key goes down, the corresponding number button on the form should look like it is depressed as well. Sorry if this is already been answered using differt jargon. I already know how to perform a button click with the keydown.
Make a test code on KeyDown event. Write down the keyboard codes you shall see from pressing 0 to 9. Then use those keyboard codes in your KeyDown's if statement
You can use a Checkbox and set the appearance to be Button. Then you can do something like this:
private void OnKeyDown(object sender, KeyEventArgs e)
{
//if key
checkBox1.Checked = true;
}
private void OnKeyUp(object sender, KeyEventArgs e)
{
//if key
checkBox1.Checked = false;
}
As far as the Keys, you can just use the KeyEventArgs.KeyCode
e.KeyCode == Keys.D0 || .. || e.KeyCode == Keys.D9

Detect Key in KeyUp event

I have a textbox on a form where I'm trying to detect the keys the user types in. The TextBox is multilined with wordwrap on. I don't want the user the press the enter key (as I want all text entered on ONE line, wrapped) so I used the following code:
private void txtPlain_KeyPress(object sender, KeyPressEventArgs e) {
if (e.KeyChar == (char)13) {
MessageBox.Show("Enter keys are not allowed");
e.KeyChar = (char)0;
}
}
This worked fine in my tests, but when I tested for CTRL+ENTER it didn't work as I'm not sure how to detect for the control key. From my googling I found that I need to use the KeyUp/Down events so I now have the following Code:
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
//if (e.KeyData == (Keys.Control | Keys.Enter)) {
if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {
MessageBox.Show("Enter keys are not allowed:");
//e.KeyValue = Keys.None;
}
}
The first commented out line didn't work for some reason so if anyone could explain why this would be useful.
The problem with the KeyUp/Down event is that I don't know how to REMOVE the enter key from the text - unlike the KeyPress event when I can set the KeyChar to zero. The event captures both the Enter and Ctrl+Enter keys, but the cursor still goes to the next line in the TextBox.
Thanks for any help on this.
Hmm, there's no reason to disallow the Enter key by handling the KeyDown or KeyUp events. You can simply set the AcceptsReturn property of the textbox control to False. This will prevent a multiline textbox from responding to a press of the Enter key.
Of course, this doesn't solve the problem of Ctrl+Enter. In fact, that's the expected way to create a new line when the AcceptsReturn property is set to False. To solve that, you will need to handle one of the keyboard events and prevent the control from receiving this input.
KeyDown is a good place to start. What you want to do is filter out any keyboard events that include the Keys.Enter flag. That will catch them no matter which other modifier key they might be combined with. Then, once you've found an Enter keypress, you want to set the e.Handled property to True in order to prevent it from being passed on to the control.
But unfortunately, we're not quite done yet. The textbox control tries to handle certain keys internally, and you're not going to be able to override that in a key event handler method. You also need to tell the control not to interpret that particular key as an input key. There are two primary ways of doing this. The first (and recommended way) is to inherit from the base TextBox class to create your own custom control, and then override the protected IsInputKey method. The second (somewhat simpler) way is just to handle the PreviewKeyDown event, and set the IsInputKey property to False.
Sample code:
private void txtPlain_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
// Check if the KeyCode value has the Keys.Enter flag set
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
// Set the IsInputKey property to False
e.IsInputKey = false;
}
}
private void txtPlain_KeyDown(object sender, KeyEventArgs e)
{
// Check if the KeyCode value has the Keys.Enter flag set
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
// Show the user a message
MessageBox.Show("Enter keys are not allowed in this textbox.");
// Prevent the key event from being passed on to the control
e.Handled = true;
}
}
And, though I assume this is for testing purposes only, you definitely want to take that MessageBox call out of there for production code. Find another way to alert the user that their input was not allowed, such as a short beep sound and an ErrorProvider component placed next to the textbox. Showing a message box is very jarring, and not very user-friendly. See my answer here for other hints and tips.
private void txtPlain_KeyUp(object sender, KeyEventArgs e) {
//if (e.KeyData == (Keys.Control | Keys.Enter)) {
if (e.KeyCode == Keys.Enter || (e.KeyCode == Keys.Enter && e.Control)) {
MessageBox.Show("Enter keys are not allowed:");
//e.KeyValue = Keys.None;
// mark event as handled
e.Handled = true;
}
}
from msdnlink
edit:
I think that you need the key down event not the key up
EDIT2
here is some tested code and it works as you wanted:
bool invalid=false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode & Keys.Enter) == Keys.Enter)
{
invalid = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (invalid)
{
e.Handled = true;
}
invalid = false;
}
The first commented out line didn't work for some reason so if anyone could explain why this would be useful.
You wanted to detect Ctrl + Enter.
if (e.KeyData == (Keys.Control | Keys.Enter)) {..
Keys.Control and Key.Enter are nothing but are some values please refer . Now doing logical or will not necessarily result to key which has been pressed. Totally illogical clause.
Ok now come to your actual problem you want to detect Enter stroke and Ctrl + Enter stroke to be treated as same.
Besides you want to undo the newline character thats been introduced. Try
PreviewKeyDown or Preview key up eventhandler with the following condition
if(e.KeyCode==Keys.Enter)
Let me know if this works

Categories

Resources