how to make command line in a multiline TextBox - c#

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

Related

Guidance text when typing in a text box in c#

I'm a starter at this so not sure if this is simple or crazly hard but what i would like is after 6 characters in a text box a - to appear and then they continue typing abit like when you do a license number in windows and it autopolutes the field as you go.
Add an event KeyPress to your textbox, so every time when you change text it will add '-' if needed. Something like this:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar) == false)
{
var tb = (sender as TextBox);
var text = tb.Text;
var blocks = text.Split('-');
var lastBlock = blocks.Last();
if (lastBlock.Length == 6)
{
tb.Text += "-";
tb.SelectionStart = tb.Text.Length;
}
}
}
There is a bug although with entering '-', as it is used as a separator.

How to format textbox to display SSN as the user types

I have a textbox which I would like to format in real time: ###-##-#### as the user types.
I have the following code:
private bool bFlag;
private void tbSSN_TextChanged(object sender, EventArgs e)
{
string str = tbSSN.Text;
if (!bFlag)
{
if (str.Length == 3 || str.Length == 6)
{
tbSSN.Text += "-";
bFlag = true;
tbSSN.SelectionStart = tbSSN.Text.Length;
}
else if (str.Length > 11)
{
tbSSN.Text = tbSSN.Text.Remove(tbSSN.Text.Length - 1);
tbSSN.SelectionStart = tbSSN.Text.Length;
}
}
else
{
bFlag = false;
}
}
The only issue is, when I hit backspace and try to enter the numbers again, it is allowing me to enter this format: #####--#### or ##-#####-##
I know I have to add a KeyPress event to ensure the above issue is resolved, but I am not sure how I would add it.
How would I code the KeyPress event?
It is a WinForm application.
Use MaskedTextBox instead of normal TextBox and define a Mask for your TextBox.
yourMaskedTextBox.Mask = "000-00-0000";

Collect multiple keypress events

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

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;

Format a number in a Textbox on Enter key press

In a windows Form, I have a text box where I put amounts, for example I would type 18369.25 then press Enter key, the textbox should be formatted to: 18 369,25
how to do that ?
Subscribe to the textbox's KeyPress event with an event handler similar to the one below:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
decimal value;
if (decimal.TryParse(
textBox1.Text,
NumberStyles.Any,
CultureInfo.InvariantCulture,
out value))
{
textBox1.Text = value.ToString(
"### ### ##0.00",
CultureInfo.InvariantCulture).TrimStart().Replace(".", ",");
}
}
}
I did some expiriments, but none seemed to work. So I came out with this solution. I know its not the best one, but at least it work (for at least what you required):
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
string s = textBox1.Text;
if (s.Contains('.'))
{
string[] arr = s.Split('.');
decimal dec = decimal.Parse(arr[0]);
textBox1.Text = string.Format("{0},{1}", dec.ToString("## ###"), arr[1]);
}
}
}
If you have any other requirements, please let me know.
bye

Categories

Resources