keydown event cant get exact length - c#

i want to ask, when iam using event keydown with counting the length of the text, it doesn't match. but when i press enter or backspace it become 9.
is there a way to make it count start from 1 instead of 0.
the code i use
private void textEdit1_KeyDown(object sender, KeyEventArgs e)
{
if (this.textEdit1.Text.Length == 10)
{
textEdit2.Text = textEdit1.Text;
this.textEdit1.Text = "";
}
label2.Text = textEdit1.Text.Length.ToString();
label1.Text = textEdit2.Text.Length.ToString();
}

You have to try the same in Key_Up event.
private void textEdit1_KeyUp(object sender, KeyEventArgs e)
{
if (this.textEdit1.Text.Length == 10)
{
textEdit2.Text = textEdit1.Text;
this.textEdit1.Text = "";
}
label2.Text = textEdit1.Text.Length.ToString();
label1.Text = textEdit2.Text.Length.ToString();
}
Because Key_Down will get executed as and when a key will be pressed and before you release the key.
And on other side Key_Up will get executed after you release the key on a keyboar so a typed character will be there in the textbox and you will get the desired result you want.

The problem is, that KeyDown-event is raised before Text-property is updated. If you need the length of the text after your key was processed you need to subscribe to another event, e.g. TextChanged.

Related

Why I can not change focus?

Im making a calculator.and for the buttons that type numbers, I wrote a condition that if the focus was on text box 1, it would enter the text there, if not, it would enter text box 2. But unfortunately the code does not work and I dont understand the problem.
(WindosForm(.Net framework))
if (textBox1.Focus() == true)
{
textBox1.Text = textBox1.Text + "1";
}
else
{
textBox2.Text = textBox2.Text + "1";
}
Subscribe to "Enter" event for your two textbox and save it. Use the same method for the two textboxes.
TextBox focusedTB;
private void textBox_Enter(object sender, EventArgs e)
{
focusedTB = sender as TextBox;
}
...
this.textBox1.Enter += new System.EventHandler(this.textBox_Enter);
...
this.textBox2.Enter += new System.EventHandler(this.textBox_Enter);
Now you know the last textbox that got focus.
private void button1_Click(object sender, EventArgs e)
{
focusedTB.Text += "1";
}
Your code appears to be attempting to check if the control is focused. The correct way to do that is:
if (textBox1.Focused)
{
// Because 'Focused' is a property. 'Focus()' is a method.
textBox1.Text = textBox1.Text + "1";
}
.
.
.
The answer to your question Why I can not change focus? is that textBox1 receives the focus every time you call this:
if (textBox1.Focus())
As mentioned in one of the comments, here's how the Focus method works:
// Summary:
// Sets input focus to the control.
//
// Returns:
// true if the input focus request was successful; otherwise, false.
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool Focus();
Note: This is a copy-paste of metadata that you can look at by right-clicking over Focus() in your code and selecting Go to Definition then expanding the definition.
I think you talk about Windows Form ?
You cannot manage like this but use event "Enter" of your textboxes, when you click inside the textbox, you give the focus to this textbox and you can do anything inside. Here I put the right focuses TextBox in a variable.
private TextBox _textBoxFocused; //this is always the righ TextBox
private void textBox1_Enter(object sender, EventArgs e)
{
_textBoxFocused = textBox1;
}
private void textBox2_Enter(object sender, EventArgs e)
{
_textBoxFocused = textBox2;
}

How can I remove a character from a C#.net WPF textbox before it's shown?

I have a project in C#.net using a WPF textbox that validates a character like * as the first character entered. If this character is entered, the rest of the text is good but I cannot show nor use the character. How can I remove the character from the string early enough to not show it? I've attempted using the KeyDown event but while the event is active, there is no data to remove. And if I use the KeyUp event the data is shown for a second. I've previously used a KeyPress event in VB6 to achieve this which worked because the value was simultaneously in the code but not in the textbox. As far as I can tell a WPF textbox does not have this event. What can I do?
Code:
private void UserInput_KeyUp(object sender, KeyEventArgs e)
{
//get ascii value from keyboard input
int Ascii = (int)e.Key;
//get char value to know what to remove as a string
char CharAscii = (char)Ascii;
If(Ascii == InputPrefix)
{
PrefixValidated = true;
UserInput.Text = UserInput.Text.Replace(CharAscii.ToString(), string.Empty);
}
}
The same code is in the KeyDown event and I've tried it using one or the other and both.
it may be a bit of a rough solution but you could use a PreviewTextInupt event I belive.
private bool PrefixValidated = false;
private string CheckUserInput;
private void TextBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
CheckUserInput = CheckUserInput + e.Text;
if (CheckUserInput.ElementAt(0).ToString() == "*" && e.Text != "*")
{
e.Handled = false;
}
else if (CheckUserInput.ElementAt(0).ToString() == "*")
{
PrefixValidated = true;
e.Handled = true;
}
else
{
e.Handled = true;
}
}
Thanks to Dark Templar for helping with the discovery of this solution. Using PreviewTextInput and validating the character only if there are no other characters in the textbox seems to give the correct result.
Setting e.Handled = true stops the character from actually entering the textbox even for a second so the user is never aware of the prefix.
Code:
private void UserInput_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
//if this is the first character entered, the textbox is not yet populated
//only perform validation if the character is a prefix
if (UserInput.Text != "")
return;
char CharAscii = (char)ScannerPrefix;
if (e.Text == CharAscii.ToString())
{
PrefixValidated = true;
e.Handled = true;
}
}

Allow Only Barcode Scanner and Eliminate Keyboard Input

I have made a Windows Form application with a textbox which uses Barcode scanner to get any input value. I want user to use only Barcode Scanner to fill any value in it, and don't want to enter any input using my regular keyboard.
Since my Barcode works mimics as a keyboard, so disabling my regular keyboard will also disable my Barcode scanner to work.
I've searched manywhere to implement this, and found few answers were suggesting to add a Stopwatch/Timer to eliminiate all keypress which occurs within 50milliseconds, since Barcode can scan all values within 50 milliseconds, but no human can type faster than 50 miliseconds.
I also tried this way, but this fails when I randomly punches my fingers on keyboard keys, it reads out since some of keys fired within 50miliseconds.
Also tried below code but even this does not work as expected for me
private void rtBoxInput_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
}
Please suggest some good way to implement this?
The basic idea is to check:
if KeyUp and KeyDown events are fired of same keys and within specified time (say 17milliseconds), as this can be only done using Barcode scanner.
No one can trigger KeyDown and KeyUp event of same key within 17 milliseconds. For example it will take more than specified time for someone to Press and Release same key, however he can hit punch to keyboard that will push multiple keys all together and trigger their KeyDown and KeyUp events, but all no keys will have KeyUp and KeyDown events fired synchronously. So by this way you can detect whether input made by regular keyboard or barcode scanner.
Please have a look below:
public partial class BarcodeReader : Form
{
char cforKeyDown = '\0';
int _lastKeystroke = DateTime.Now.Millisecond;
List<char> _barcode = new List<char>(1);
bool UseKeyboard = false;
public BarcodeReader()
{
InitializeComponent();
}
private void BarcodeReader_Load(object sender, EventArgs e)
{
this.KeyDown += new KeyEventHandler(BarcodeReader_KeyDown);
this.KeyUp += new KeyEventHandler(BarcodeReader_KeyUp);
}
private void BarcodeReader_KeyUp(object sender, KeyEventArgs e)
{
// if keyboard input is allowed to read
if (UseKeyboard && e.KeyData != Keys.Enter)
{
MessageBox.Show(e.KeyData.ToString());
}
/* check if keydown and keyup is not different
* and keydown event is not fired again before the keyup event fired for the same key
* and keydown is not null
* Barcode never fired keydown event more than 1 time before the same key fired keyup event
* Barcode generally finishes all events (like keydown > keypress > keyup) of single key at a time, if two different keys are pressed then it is with keyboard
*/
if (cforKeyDown != (char)e.KeyCode || cforKeyDown == '\0')
{
cforKeyDown = '\0';
_barcode.Clear();
return;
}
// getting the time difference between 2 keys
int elapsed = (DateTime.Now.Millisecond - _lastKeystroke);
/*
* Barcode scanner usually takes less than 17 milliseconds as per my Barcode reader to read , increase this if neccessary of your barcode scanner is slower
* also assuming human can not type faster than 17 milliseconds
*/
if (elapsed > 17)
_barcode.Clear();
// Do not push in array if Enter/Return is pressed, since it is not any Character that need to be read
if (e.KeyCode != Keys.Return)
{
_barcode.Add((char)e.KeyData);
}
// Barcode scanner hits Enter/Return after reading barcode
if (e.KeyCode == Keys.Return && _barcode.Count > 0)
{
string BarCodeData = new String(_barcode.ToArray());
if (!UseKeyboard)
MessageBox.Show(String.Format("{0}", BarCodeData));
_barcode.Clear();
}
// update the last key press strock time
_lastKeystroke = DateTime.Now.Millisecond;
}
private void BarcodeReader_KeyDown(object sender, KeyEventArgs e)
{
//Debug.WriteLine("BarcodeReader_KeyDown : " + (char)e.KeyCode);
cforKeyDown = (char)e.KeyCode;
}
}
Check Here.. GitHub Link
If your barcode mimics a keyboard - there is no way you can find which one is inputing text in your TextBox. Can your barcode scaner add some prefix to scanned code? If yes - I think this is a best option in combination with 50ms timer.
What you can do is to handle your Barcode directly on your form using a KeyPress Event and disable your TextBox :
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
barcode = string.Empty;
try
{
barcode += e.KeyChar;
if (lastTime > new DateTime())
{
if (DateTime.Now.Subtract(lastTime).Milliseconds > 30)
{
f1 = false;
}
else
{
f1 = true;
}
}
lastTime = DateTime.Now;
/*
Test your Barcode, and if it matches your criteria then change your TextBox text
TextBox1.Text = barcode;
*/
}
catch (Exception ex)
{
MessageBox.Show("Something went wrong");
}
}
Don't forgot to set Form1.KeyPreview = true and it should do the trick !

Replace pressed key in TextBox to another C#

How can I replace pressed 'decimal point' key from numpad to always return '.' independent of regional setting. I want that works only for one (specific) TextBox not all in application.
It's possible to accomplished this without creating own control?
This is a possible solution (most possibly not the best one, but one that should work) that would add a . character to a textbox if the decimal key on the numpad is pressed, if the , key is pressed it still adds the , character to the textbox.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Decimal)
{
e.SuppressKeyPress = true;
textBox1.Text += ".";
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.SelectionLength = 0;
}
}
The SuppressKeyPress prevents that the pressed key is sent to the textbox. Then you add the desired character to the textbox. The SelectionStart and SelectionLength properties are set to move the cursor to the end of the string in the textbox.
Hope that helps
EDIT:
As cdkMoose pointed out the flaw with this approach is that the .character is always added to the end of the string, if it is desired to add the .character anywhere in the string the code could be used like this:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Decimal)
{
e.SuppressKeyPress = true;
var caretPosition = textBox1.SelectionStart;
textBox1.Text.Insert(caretPosition , ".");
textBox1.SelectionStart = caretPosition + 1;
textBox1.SelectionLength = 0;
}
}
In order to do this, you simply need to handle the KeyDown event, supress the activated key if its the numpad decimal, and then simply send the new key you want.
It's pretty straightforward, the following links should give you enough pointers to actually write some code:
Keys
Control.KeyDown
KeyEventArgs
SendKeys
Once you've written something, you can ask a new question about any specific dificulties you might encounter.
Look at this.
You can handle KeyDown event and if is , on numpad cancel event and send new with '.'.

How to make TextBox handle text like a hyperterminal in c#?

When the user enters a character with the TextBox in focus, I do not want the character to show up on the TextBox at all and I don't want to use the Clear() method as there may be other text in the TextBox I don't want erased. so far I've tried:
private void WriteBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // enter key pressed
{
WriteBox1.Text = "";
}
// Code to write Serial....
String writeValues = WriteBox1.Text;
String withoutLast = writeValues.Substring(0, 1);
WriteBox1.Text = withoutLast;
}
This leaves the last letter entered in writeBox1. I need it to delete all characters entered.
I've also tired:
writeValues.Replace(writeValues, "");
WriteBox1.Text = writeValues;
Try setting Handled property on eventargs. Set Handled to true to cancel the KeyPress event. This keeps the control from processing the key press.
example :
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;
}
}
https://msdn.microsoft.com/ru-ru/library/system.windows.forms.keypresseventargs.handled%28v=vs.110%29.aspx

Categories

Resources