Detect keypressing in a textbox and converting user text to a string - c#

I want to write something in a TextBox, then I want to press Enter and convert the input into a string.
How do you do this in WinForms?

For starters, input into a TextBox is already a string and is stored in the Text property. So that part is easy.
Triggering off of the "Enter" key is another story however. The easiest way is with the PreviewKeyDown event. Assign something like the following handler to your text box's PreviewKeyDown event (either in code-behind or through the designer):
void HandleKeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string input = (sender as TextBox)?.Text;
//Your logic
e.IsInputKey = true; //Don't do standard "Enter" things
}
}
The reason you use PreviewKeyDown is that the later events (KeyDown, KeyPress, KeyUp) won't trigger on "Enter" because its not a "InputKey". The linked documentation explains is in fuller detail.
Notes:
If you want the standard handling of "Enter" to continue, then don't set IsInputKey to true.
The first line of the if statement says "Cast the control that raised this event to TextBox and get it's Text property." You could instead use the TextBox's name, or a number of other things.
The ?. is in case the cast fails due to the control not actually being a TextBox (input will be null in that case). This is only valid syntax in C# 6.

The text in the textbox would already be a string. You can grab the text value of the textbox by simply grabbing the .Text property.
See https://msdn.microsoft.com/en-us/library/a19tt6sk(v=vs.110).aspx for more info.

Related

C# KeyPress Event doesn't copy last character from text box to form's text property

Situation:
A form has a text box in which the user must type some text. This text box has a KeyPress event in which the Form's text property changes to the text that the user types with each keystroke.
Here's the code for the textbox's KeyPress Event:
private void tbGameTitle_KeyPress(object sender, KeyPressEventArgs e)
{
this.Text = textBox1.Text;
}
Problem:
The last character the user types doesn't get copied to the Form's text. Example:
textBox1.Text = "The War of 1812"
Form2.Text = "The War of 181"
The "2" at the end of "The War of 1812" in textBox1.Text doesn't get copied to Form2.Text.
How can I get the whole text string to copy from textBox1.Text to Form2.Text?
Try using the TextChanged event instead of KeyPress. You're a fraction too early when using the latter, since the Text property gets updated after the key press has been handled.
That is because KeyPress gets fired before the character actually "enters" textBox1. If you watch as you type, you'll notice that Form2 will always be a character behind textBox1. You'll want to use the TextChanged event instead, which gets fired after each change to the text in textBox1.

TextBox Events in C#

I have a TextBox. After leaving the textBox the first character should be a capital Letter.
Three Events work as same. They are Leave,Validating and Validated.
if (txtLocl.Text.Length > 0)
txtLocl.Text = txtLocl.Text.Substring(0, 1).ToUpper() + txtLocl.Text.Substring(1);
Which event of these 3 events should I use?
You can subscribe to the Control.Leave event which will be fired when the control loses focus. Originally, I thought using Control.LostFocus would be the most appropriate event to use but it is not available via the designer meaning you would need to manually subscribe to the event which is a bit ugly and unconventional in my opinion.
private void inputTextBox_Leave(object sender, EventArgs e)
{
if (inputTextBox.Text != string.Empty)
{
string input = inputTextBox.Text;
inputTextBox.Text = input.First().ToString(CultureInfo.InvariantCulture).ToUpper() +
string.Join(string.Empty, input.Skip(1));
}
}
You sound like you're interested in Control.Validating. The advantage of using Control.Validating is that you can utilize the event handler's given argument; CancelEventArgs and set the Cancel property to true. What this will do is stop the control from losing focus and forcing the user to enter a valid value. I don't think this is appropriate for your application as you are not really validating anything but formatting the input.
private void inputTextBox_Validating(object sender, CancelEventArgs e)
{
if (inputTextBox.Text == string.Empty)
{
statusLabel.Text = "The given input is not valid.";
e.Cancel = true;
}
}
Bear in mind that when the form closes, all controls subsequently lose focus and the Control.Validating event is fired which could stop the Form closing until all fields pass their relative validation checks. If you find yourself needing to avoid this behavior a quick search will prevail.
There are many other events also available.
As said by MSDN, When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:
1) Enter
2) GotFocus
3) Leave
4) Validating
5) Validated
6) LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
1) Enter
2) GotFocus
3) LostFocus
4) Leave
5) Validating
6) Validated
If the CausesValidation property is set to false, the Validating and Validated events are suppressed.
textBox1_Leave is appropriate for you.
Check the events and description about textboxes over here>>
http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox_events.aspx
Hope its helpful.
You might want to subscribe to LostKeyboardFocus event (in WPF) or Leave event (in WF).
I'd suggest using the Leave because I assume you aren't validating the value, but formatting it. Validating and Validated should contain code for validation and the aftermath of validation respectively, IMO.

Inserting a TAB space into a TextBox

I have seen few tutorials that claim to solve this issue online but they do not work. I would like to insert a TAB space when the TAB key is pressed, into my multiline TextBox.
A dudes response from Microsoft was that, by design, Metro apps will bring focus to the next control if you press TAB inside a TextBox. Now, this would make sense, if you were pressing TAB on a Single-line TextBox. But in a multiline TextBox? Don't you think it's more likely that the user will want to insert a TAB?
And yes, I know, you can insert a TAB space in a Metro TextBox by pressing Ctrl+TAB. But that is error prone, since most of us are used to just pressing TAB, and old habbits die hard sometimes.
Here is my issue. I have a text editor feature of my app where the user may need to enter large amounts of data. And you know what people are like, they like to separate things to make their text documents more readable and it's very uncomfortable and more tedious to use Ctrl+TAB. So I would like to know if anybody can help with a workaround for this (it can't involve a RichTextBox, though)?
Also, if I manage to find a workaround, will this increase the chances of my app release being rejected by the Store?
Subscribe to the KeyPress event of your TextBox, capture the Tab key by inspecting the KeyCode of the pressed key, and then set the Handled property of the KeyEventArgs to true so the key isn't passed onto any other controls.
Use SendKeys to send a "Tab" character to the TextBox to mimic the behavior of pressing "Ctrl+Tab", like you said:
TextBox_KeyPress(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
e.Handled = true;
SendKeys(^{TAB});
}
}
The carrot (^) represents the CTRL key.
richTextBox1.AcceptsTab = true;
in your KeyPress event of your textbox control. Make sure that you have the property set true for multiline on the textbox control
This would work if you are using a RichText Control which is what I would suggest
if (e.Key == Windows.System.VirtualKey.Tab)
{
e.Handled = true;
string SelectionText = "";
TextBox.Document.Selection.GetText(Windows.UI.Text.TextGetOptions.None, SelectionText);
TextBox.Document.Selection.TypeText(char(9) + SelectionText);
}

What validation events are raised for the TextBox control?

Is there any event that fire when the value of the textbox change from a peace of code and when the textbox is validated or lost the focus and the event don't fire on the key press,because I have a lot of calculation and It's not possible to do it on every key press
Use TextChanged for text changed.
Use LostFocus for when textbox looses focus.
Use Validating or Validated for validation.
Here is the order in which events are called for TextBox:
// Reference : http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx
1) Enter
2) GotFocus
3) Leave
4) Validating
5) Validated
6) LostFocus
This should help you decide where you want to put your code.
There's no event that will fulfill your requirement of being raised when the textbox's value is changed programmatically through code, but not when text is typed into it by the user. The TextChanged event is going to be raised either way (this is fairly intuitive—the text value is changing, and the computer doesn't know or care what is responsible for changing it). As the documentation for this event indicates:
User input or setting the Text property to a new value raises the TextChanged event.
If you need to run custom validation logic when you add text to your textbox in code, you will need to invoke whatever method contains the validation logic yourself. Extract it into a separate method, which you call from the Validating/Validated event handler and from all of the places in your code where you set the textbox's Text property.
As a supplement to the other answers that have already been posted, I strongly recommend using either the Validating (if you want to be able to cancel the validation) or Validated events to handle the textbox losing focus, rather than the somewhat more obviously named LostFocus event.
You can use the LostFocus or Validated events.
Use a member variable.
private bool _changeByCode;
public void DoSomeChanges()
{
_changeByCode = true;
textbox1.Text = "Hello";
_changeByCode = false;
}
public void Textbox1_Change(object source, EventArgs e)
{
if (_changeByCode)
return;
//do your validation here.
}

create textbox one by one on enter keypress event

am using c# vs-2005
am on project to create textbox one by one on form1 and am success on button click event my code is below.
// declare location point of textbox on Global Area.
private point txtboxstartpoint=new point(10,10);
private void button_click (Object sender,EventArgs)
{
Textbox tbx = new TextBox();
tbx.Location= txtboxstartpoint;
tbx.size=new size (200,20);
this.panel1.control.add(tbx);
txtboxstartpoint.y += 25;
}
this works fine on button click event but problem is on keypress event like on enter
i wants to create textbox on enter one by one. and for that i assume that any method have
to create and call enter keypress event on newly created control like textbox to create
another new textbox below the previous one.
Kindly help me. suggest proper code for the same.
It's very hard to understand your question, but let's try some guessing:
You have a form, and if a user presses some specific key, you'd like to create a new TextBox and show it on your form regardless which control has currently the focus in your form.
If this statement is true, you can set Form.KeyPreview to true. And add an event handler to Form.KeyDown.
Due to the fact, that you set the preview to true you'll get every keyboard hit before it will be give further to the control that has currently the focus. So here you can check if the key that was pressed is the one you're listening for. And if yes, just call your TextBoxFactory and set the e.Handled to true to prevent that this key stroke will additionally reach the currently focused control.
I use the KeyDown event, to intercept the 'F1' key to provide my small help in a very small programm. Here is the code:
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F1)
{
//Your Code here
}
}

Categories

Resources