how to make a multiline textbox not accept Enter and Backspace - c#

I have a multiline textbox which shouldn't accept alphabets, numbers, newline(enter key) and backspace. In short, the textbox.Text shouldn't be editable. But I do want the textbox to accept two shortcut keys - control and control+R. One way I can make the textbox un-editable is by making it read-only. But then the textbox wont accept any keystroke at all. In short, my shortcuts ( control and control+R) wont work( Control + R) with read-only method.
Can anyone help in this regard. That's all I have to do.
One thing I could do here is not to make the textbox read-only and then restrict the characters(alphabets and digits) that could be inputted in the textbox. With this code:
private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
{
// only modifier keys, escape, enter, backspace etc is accepted now
e.Handled = !char.IsControl(e.KeyChar);
}
private void txtResult_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control == true)
{
if (e.KeyCode == Keys.R)
{
// do something
}
else
{
//do something
}
}
if (e.KeyCode == Keys.Escape)
{
//do something
}
}
With this technique I can get the shortcuts(control and control+R) working. But the trouble with this method is that Enter and Backspace keys work as well making it possible to edit the text of textbox. How can I specifically restrict Enter and Backspace key being registered from the textbox, but let Control and Escape??

did you try SuppressKeyPress = true ?
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control == true)
{
if (e.KeyCode == Keys.R)
{
// do something
}
else
{
//do something
}
}
else
e.SuppressKeyPress = true;
}

Since you are handling the keys in the KeyDown event handler, why not have your KeyPress handler return that all keystrokes are handled?
So just set e.Handled = true no matter what. I believe the backspace and enter would be interpreted as control characters, also.

The Enter and Backspace keys won't work if the textbox is set to ReadOnly, as you suggested early on in the question that you had done. Make sure the property is still set to true. You can either set it in the Properties window, or through code like so:
myTextBox.ReadOnly = true;
Then, you need to handle the KeyDown event for the textbox control, and watch for the specific keys that you're interested in. Something like this:
private void myTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control)
{
if (e.KeyCode == Keys.R)
{
MessageBox.Show("Pressed Ctrl+R");
}
else
{
MessageBox.Show("Pressed Ctrl");
}
}
else if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("Pressed Esc");
}
}
This works exactly as expected, as long as the textbox is set to read-only. No other keys are recognized, and the user cannot change or modify any of the text in the textbox. You don't need to suppress the keypresses, as the control is already doing that when you set it to read-only. You also don't need to handle both the KeyDown and KeyPress events. KeyPress won't work for you anyway, as it doesn't let you handle control characters.

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;
}
}

Ignore KeyDown if the text of a RichTextBox won't change

I need to determine whether a key, when it is pressed, will change the control's text or not; I need to ignore key presses like Ctrl+Z or Esc, but I need to know which key was pressed if the text changed.
Is there any way to know that in the KeyDown event? Currently, I'm using a flag, set on KeyDown and checked on TextChanged, but I was wondering if there is a better way?
You're looking for Char.IsControl
private Keys lastKey = Keys.None;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
lastKey = e.KeyData;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar))
{
e.Handled = true;//prevent this key press
Keys pressedKey = this.lastKey;
//Do your stuff with pressedKey here
}
}
You could catch the KeyPress event on the text box and if it is a valid key you would set e.handled = false and if it was a bad key you would set e.handled = true.
example from: here
private void keypressed(Object o, KeyPressEventArgs e)
{
// The keypressed method uses the KeyChar property to check
// whether the ENTER key is pressed.
// If the ENTER key is pressed, the Handled property is set to true,
// to indicate the event is handled.
if (e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
}
}
There are some keys which produce a Control char but they also change the text, for example BackSpace. They have another difficulty: if the textbox is empty, pressing them (for example BackSpace) doesn't change the text; so it breaks the previous rule. So Control characters are not naive to deal with and build a rule upon.
Moreover, consider Ctrl + C or Shift + Insert or similar cases. The 'C' key is somehow seductive; it is like pressing 'C' changes the text but if it was pressed with 'Ctrl', it actually didn't change the text. We should check the Modifiers.
Perhaps you can find other difficulties to deal with and I think the flag approach is good enough.

How to change the focus inside a form and make the new control deal with the key pressed?

I have a form with a search box and a datagridview with the results.
What I need is the search box to always get the focus whenever I press a char or number key, and then process the key. So, for instance, if my focus is on the datagrid, and I press a char, it'll go to the search box. (Additionally, whenever the Up or Down arrows are pressed in the form, the focus will go to the datagrid, but I got no problem with that.)
Now, the code below will work as a charm for chars. When I get to the numbers, though, I can't do it the same way (as my e.KeyCode.ToString() will not give me the number, but a "d0" or "numpad0").
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (!this.tbxSearch.Focused)
{
if ((e.KeyCode >= Keys.A) && (e.KeyCode <= Keys.Z))
{
this.tbxSearch.Focus();
this.tbxSearch.Text = (e.Shift) ? e.KeyCode.ToString() : e.KeyCode.ToString().ToLower();
this.tbxSearch.SelectionStart = this.tbxSearch.Text.Length;
}
}
}
Of course, I might do it just about the same way, and simply get the last char in the "e.KeyCode.ToString()", but it doesn't seem alright to me. I mean, there must be a simpler way of just changing the focus and then making the control deal with the key pressed.
I've tried making it in the PreviewKeyDown event, but it won't be triggered by the form (even with the KeyPreview property set to true):
private void Form_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if ((e.KeyCode == Keys.Down) || (e.KeyCode == Keys.Up))
this.dgvResults.Focus();
else
this.tbxSearch.Focus();
}
So I was left wondering: how can I change the focus on a form and let the new control deal with the key?
You can check if a key is a digit like this:
private Keys[] numericKeys =
{
Keys.D1,
Keys.D2,
Keys.D3,
Keys.D4,
Keys.D5,
Keys.D6,
Keys.D7,
Keys.D8,
Keys.D9,
Keys.D0,
Keys.NumPad0,
Keys.NumPad1,
Keys.NumPad2,
Keys.NumPad3,
Keys.NumPad4,
Keys.NumPad5,
Keys.NumPad6,
Keys.NumPad7,
Keys.NumPad8,
Keys.NumPad9
};
...
bool isDigit = numericKeys.Contains(e.KeyCode);
or like this:
bool isDigit = Char.IsDigit((char)e.KeyCode);
or:
bool isLetterOrDigit = char.IsDigit((char)e.KeyCode);

Richtextbox deletes selected text

I have the following code:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
}
}
When I press the N key , the selected text is replaced with "n". I read this Selecting text in RichTexbox in C# deletes the text ,but it had no effects.
I am using Windows Forms.
Likely, you will need e.Handled = true; in this to stop the event.
http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.handled.aspx
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
e.Handled = true;
}
}
Try it yourself:
Open up the editor, type some text, mark some of this text and press N. What happens? The marked text is replaced with n.
The same thing happens in your RichTextBox. Important to understand here is, that with the event you set up, you only add some functionality and leave the default event handling (handled by the OS) intact.
So with your code, on a key press you just do
richTextBox1.Select(1, 3);
which selects some characters and afterwards the default event handling kicks in. Thus there is some marked text which gets replaced with N.
So, you simply have to mark the event as handled by yourself. Not using the Handled-property, but with the SuppressKeyPress-property.
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.N)
{
richTextBox1.Select(1, 3);
e.SuppressKeyPress = true;
}
}
The documentation of Handled clearly states:
If you set Handled to true on a TextBox, that control will
not pass the key press events to the underlying Win32 text
box control, but it will still display the characters that the user typed.
Here is the official documentation of SuppressKeyPress.

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