Collect multiple keypress events - c#

Hello this code down append text to textBox after key is pressed. It writes one line for each key press. May i ask if there is any good solution to collect for example 5 key press and write them in one line?
private void User_KeyPress(object sender, KeyPressEventArgs e)
{
textBox.AppendText(string.Format("You Wrote: - {0}\n", e.KeyChar));
textBox.ScrollToCaret();
}
For example MOUSE wouldn't be written like:
You Wrote: M;
You Wrote: O;
You Wrote: U;
You Wrote: S;
You Wrote: E
But the output will be:
You wrote: MOUSE

Maybe something like:
string testCaptured = string.Empty;
int keyPressed = 0;
private void User_KeyPress(object sender, KeyPressEventArgs e)
{
if (keyPressed < 5)
{
testCaptured += e.keyChar;
keyPressed++;
}
else
{
textBox.Text = string.Format("You Wrote: - {0}\n", testCaptured);
textBox.ScrollToCaret();
}
}

Don't call textBox.AppendText. Appending adds to an existing string and combines them.
You want to write something like textBox.Text = String.Format(...)
You should create a private variable in your object to keep track of all the characters and append to that. The class which owns your User_KeyPress method should have a variable like the following:
private string _keysPressed = String.Empty;
Now in your method you can append and output like so:
private void User_KeyPress(object sender, KeyPressEventArgs e)
{
_keysPressed += e.KeyChar;
textBox.Text = String.Format("You Wrote: - {0}\n", _keysPressed);
textBox.ScrollToCaret();
}

You could buffer the key presses until you reach a threshold and then output the entire buffer's contents.
e.g.
Queue<char> _buffer = new Queue<char>();
private void User_KeyPress(object sender, KeyPressEventArgs e)
{
_buffer.Enqueue(e.KeyChar);
if(_buffer.Count > 5)
{
StringBuilder sb = new StringBuilder("You Wrote: ");
while(_buffer.Count > 0)
sb.AppendFormat(" {0}", _buffer.Dequeue());
Console.WriteLine(sb.ToString());
}
}

Related

Looking to call method with parameter to take in specified text box

I am creating a Windows Form Application and I want to create a method to be able to pass in a specified text box from a _Click event. Such as below: My Method is AddTo() and I want to call from the 2 click events which have 2 separate text boxes. I want to be able to pass in the correct text box.
void AddTo(string ctrl)
{
int num= int.Parse(ctrl);
num++;
ctrl = num.ToString();
}
private void btnAddLevel_Click(object sender, EventArgs e)
{
AddTo(TextBox1.Text);
}
private void btnAddSecond_Click(object sender, EventArgs e)
{
AddTo(TextBox2.Text);
}
I am pretty new to C#, is this possible to do? Thanks in advance for any help.
UPDATE:
Here is the full code with the fix below
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
txtName.Text = "0";
}
void AddTo(ref TextBox tBox)
{
if (tBox.Text.Trim().Length > 0)
{
int num = 0;
//CHECK IF THE TEXT IS CONVERTIBLE TO NUMBER
if (int.TryParse(tBox.Text, out num))
{
num++;
tBox.Text = num.ToString();
}
}
}
private void btnAddUnit_Click(object sender, EventArgs e)
{
AddTo(ref txtName);
}
}
Use ref key word to retain data updates for passing objects.
Try below code:
//YOUR TEXTBOX IS A REFERNCE HERE. SO THAT THE UPDATES ARE RETAINED
void AddTo(ref TextBox tBox)
{
//VALIDATED YOUR TEXT BOX IF DATA EXISTS BEFORE UPDATING
if (tBox.Text.Trim().Length > 0 )
{
int num = 0;
//CHECK IF THE TEXT IS CONVERTIBLE TO NUMBER
if (int.TryParse(tBox.Text, out num))
{
num++;
tBox.Text = num.ToString();
}
}
}
While calling
//USE REF WHILE CALLING
AddTo(ref textBox1);//textbox object

Fill a textbox based on another textbox text

I have TextBoxA and TextBoxB. What i want to do is , whenever i put a number (yes, both of the textboxes values are always integers) in TextBoxA , TextBoxB should "autocomplete" with value (100-TextBoxA). Same thing goes for TextBoxB. The sum of TextBoxA and TextBoxB should always be 100.
Here's what i've already tried:
static void TextBoxA_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-a).ToString();
TextBoxB.Text = text;
}
Static void TextBoxB_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-b).ToString();
TextBoxA.Text = text;
}
But it doesn't work.
Here's what you can try:
private void TextBoxA_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxA.Text, out num))
{
string text = (100 - num).ToString();
TextBoxB.Text = text;
}
}
private void TextBoxB_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxB.Text, out num))
{
string text = (100 - num).ToString();
TextBoxA.Text = text;
}
}
This will autocomplete on either TextBox on TextChanged Event.
First, i dont know why your event handlers are declared static.. its usually got to be :
private void TextBoxA_TextChanged(object sender, EventArgs e) { }
Secondly, you know if you have 2 textboxs, and each one triggers the other, you'll never go out of the TextChanged event.
To understand me more, here's an example :
1- You set TextBoxB.text = "1";2- TextBoxB.TextChanged triggers, it
sets TextBoxA.Text = "2"; 3- TextBoxA.TextChanged triggers, it sets
TextBoxB.Text = "1";
And it continues like this until i believe you'll get an Exception of memory.
EDIT : The opertator '-' works on numbers. You can't substract a number from a string. they have to be both numbers, so convert them first.
EDIT 2 :
Here's a code i wrote that works fine
private void textBox1_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox1.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox2.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox2.Text = m.ToString();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox2.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox1.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox1.Text = m.ToString();
}
}
Try this. This is a more efficient and elegant way I'd choose using lambda expressions, without repeating the method:
private void onChangeDoSum(object sender, EventArgs e,
TextBox substractNumber, TextBox sumNumber)
{
sumNumber.Text = (100 - Int32.Parse(substractNumber.Text)).ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox1, textBox2);
textBox2.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox2, textBox1);
}
Alternatively use Int32.TryParse to prevent unexpected results.
I think you can do something like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = (100 - Int32.Parse(textBox1.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = (100 - Int32.Parse(textBox2.Text)).ToString();
}
when I see that static word I think you have tried to create these method by yourself and you forgot to add
textBox1.TextChanged += textBox1_Changed;
// I saw other post where you wrote that it could raise exception and fall. Of course it can. You can use if condition like
textBox1.Text != null && textBox1.Text != ""
before value would be changed or TryParse() method

How to prevent crashing from a invalid input in C#

I made a simple application to add 2 numbers together but when I add two letters together or a invalid sign it crashes the program. How do I create a message box showing something saying "please put in a number" when someone inserts a letter
Here's my code:
public partial class frmAdd : Form
{
string first;
string second;
public frmAdd()
{
InitializeComponent();
}
private void btnFirst_Click(object sender, EventArgs e)
{
first = txtNumber.Text;
}
private void btnSecond_Click(object sender, EventArgs e)
{
second = txtNumber.Text;
}
private void btnResult_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(first);
int b = Convert.ToInt32(second);
int c = a + b;
txtResult.Text = c.ToString();
}
}
Use TryParse instead:
private void btnResult_Click(object sender, EventArgs e)
{
int a, b;
if (int.TryParse(first, out a) && int.TryParse(second, out b))
{
int c = a + b;
txtResult.Text = c.ToString();
}
else
{
MessageBox.Show("Invalid Input!");
}
}
Or perhaps a better method would be to trap the error when the user first inputs the data:
public partial class frmAdd : Form
{
int first; // changed to int
int second;
private void btnFirst_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtNumber.Text, out this.first))
{
MessageBox.Show("Invalid Input!");
}
}
private void btnSecond_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtNumber.Text, out this.second))
{
MessageBox.Show("Invalid Input!");
}
}
private void btnResult_Click(object sender, EventArgs e)
{
int c = first + second;
txtResult.Text = c.ToString();
}
}
You can use NumericUpDown control instead of TextBox - it will not allow user to input invalid data.
Or you can add validation to TextBox value after user entered something. Add ErrorProvider to your form. And subscribe to Validating event of txtNumber textbox. This event will occur when textbox loses focus. If entered text is not an integer, then error will be shown near texbox, and your button will not be clicked:
private void txtNumber_Validating(object sender, CancelEventArgs e)
{
int value;
if (!Int32.TryParse(txtNumber.Text, out value))
{
errorProvider1.SetError(txtNumber, "Value is not an integer");
return;
}
errorProvider1.SetError(txtNumber, "");
first = value; // it's better to save integer value than text
}
Validation looks like:
You can add a bit of validation to check if you can create an int from the string value passed in.
int.TryParse is a simple way of doing this.
And for the MessageBox you can just use the MessageBox calss
Example:
private void btnResult_Click(object sender, EventArgs e)
{
int a = 0;
int b = 0;
if (!int.TryParse(first, out a))
{
MessageBox.Show("first is not a number");
return;
}
if (!int.TryParse(second, out b))
{
MessageBox.Show("second is not a number");
return;
}
int c = a + b;
txtResult.Text = c.ToString();
}
Instead of using Convert.ToInt32(string), you might actually use Int32.tryParse(String, out int), as shown below:
int a, b;
a = Int32.tryParse(first, out a);
b = Int32.tryParse(second, out b);
If the conversion fails, the tryParse method will result in a zero. If it succeeds, it will give you the number which is to be found in the string.
Hope it helped you out, had to find this too in my first few days of C#.

unable to clear a textbox data

I'm not able to delete textbox data with the code below
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(char.IsDigit(e.KeyChar)==false)
{
count++;
}
if (count == 1)
{
textBox1.Text = ("");
count = 0;
}
}
tried using clear method as well the alphabet i entered stays in the textbox and when i type any key it get overwritten but i want the textbox to be empty the second time and the prev data to be removed
you just need to say you've handled the event:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == false)
{
count++;
}
if (count == 1)
{
textBox1.Text = ("");
count = 0;
e.Handled = true; // this bit fixes it
}
}
use textBox1.Text = ""; OR textBox1.clear();
This will clear your textbox.
You are doing it wrong. You can just paste in a bunch of letters with Ctrl+V. Delete the KeyDown event and create a TextChanged event. This code should accomplish what you are attempting. Please tell me if there is any more details and I will add to my answer.
private void textBox1_TextChanged(object sender, EventArgs e)
{
foreach (char c in textBox1.Text)
if (!char.IsDigit(c)) { textBox1.Clear(); break; }
}
Add this to your text box key press event your problem will be solved
e.handle = true;

how to make command line in a multiline TextBox

I am working with some electronics instruments using GPIB. I can communicate with instruments like this:
K2400.WriteString("*IDN?", true);
textBoxK2400.Text += K2400.ReadString() + Environment.NewLine;
The first line will execute a command, and in the second line I add the response of the last command to the textbox. How can I write the command in the textbox directly and add the response?
For example, if the user command entered after an indicator like ">>" and hitting ENTER, the response should be added in the next line of textbox.
So how can I read the last line of a textbox and add the respone in a new line? I am looking for a method like:
private void Execute(string command)
{
K2400.WriteString(command, true);
textBoxK2400.Text += K2400.ReadString() + Environment.NewLine;
}
Use two Text boxes(textbox and a listbox might be better) but make them look as "one" textbox.. If using WPF it could look pretty nice and in Windows form possible at least.
Did a quick test..
And with this code for KeyPress event for the textbox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
listBox1.Items.Add(textBox1.Text);
textBox1.Text = String.Empty;
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
You could try this:
private void textBoxK2400_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
string command = textBoxK2400.Text.Split('\n').LastOrDefault();
if (!String.IsNullOrEmpty(command) && command.StartsWith(">>"))
{
K2400.WriteString(command.Substring(2), true);
textBoxK2400.Text += K2400.ReadString() + Environment.NewLine;
textBoxK2400.Text += ">>"; // It's not necessary
}
}
}
private void Execute(string command) { K2400.WriteString(command,
true); textBoxK2400.Text += K2400.ReadString() + Environment.NewLine;
}
this is it. I'd just recommend to 'buffer' a part of the text, not all, because it could be long by the end. You can split it to lines before and take a number of lines (i. e. 10).
And don't forget to make the field black and the text green, it looks much more professional when the command field is decorated such way.
Well first i would suggest a RichTextBox to use.
To capture ENTER you should use KeyPress Event .
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
string LastLine = richTextBox1.Lines[richTextBox1.Lines.Length-2];
if (LastLine.StartsWith(">>"))
{
//here you can filter the LastLine
K2400.WriteString(LastLine, true);
richTextBox1.AppendText(K2400.ReadString() + Environment.NewLine);
}
else
{
//here you can unwrite the last line
string[] totalLines = richTextBox1.Lines;
richTextBox1.Text = "";
for (int i = 0; i < totalLines.Length - 2; i++)
{
richTextBox1.AppendText(totalLines[i]+Environment.NewLine);
}
MessageBox.Show("That was not a valid command");
}
}
}

Categories

Resources