I'm currently trying to make an application (just for learning purposes to try to get used to C# because I'm kinda new) and I've wanted to create a sort of to say Terminal within the Form. I've decided to try to use a text-box with multiple lines and tried using if and else statements but when I go into the text box and start typing it immediately goes to the error message that I set up for 'else' after every keystroke. I don't know what it is but I feel like I'm missing something. Any suggestions? Also, would it be possible to create my own "commands" for that application alone in itself? I'm talking about like when you type in lets say "program_speech" it will come up with a dialog asking for user input and it will basically convert text to speech with the built in Speech Synthesizer for Windows. Thanks! All help is appreciated!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Terminator //Lol Terminator Reference
{
public partial class Form1 : Form
{
private string answer;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (answer == "help")
{
MessageBox.Show("There is only 2 commands as of now and that is 'help' and 'program_speech' ");
}
else if (answer == "program_speech")
{
MessageBox.Show("Still currently under creation");
}
else
{
MessageBox.Show("Invalid Command. Please try again or type help for current available commands");
}
}
}
}
At every keystroke an event called TextChanged is raised, it goes to else condition of 'Invalid Command' because the text in that textbox at that time is neither "help" nor "program_speech". Using TextChanged is definitely not recommended.
You should use a button and its click event to check the value of textbox. Because that's the only way you can be sure that all the required text is written. It would be something like -
private void btnCheckText_Click(object sender, EventArgs e)
{
answer = textBox1.Text;
if (answer == "help")
{
MessageBox.Show("There is only 2 commands as of now and that is 'help' and 'program_speech' ");
}
else if (answer == "program_speech")
{
MessageBox.Show("Still currently under creation");
}
else
{
MessageBox.Show("Invalid Command. Please try again or type help for current available commands");
}
}
Better make a Enter Button and read in the text from the textbox, after pressing the enter button
private void Button1_Enter(object sender, EventArgs e)
{
input = textbox.Text;
//then do a switch case
Initialize answer to textbox1.text. I am assuming you have achieved it somehow. If not #Kishor's answer is the way you should do it.
This is happening because your textBox1_TextChanged will get fired every time there is even a single change in your textbox. So when you type in any letter the textbox text changes and the function is fired thus triggering your else statement. For example you type h, ==> Textbox registers the change and calls textBox1_TextChanged and since the text is not help if goes in the else part. This is repeated till hel till u completely type in help.
If you try when your textbox finally reads help it will follow the MessageBox.Show("There is only 2 commands as of now and that is 'help' and 'program_speech' "); command you specified.
As per the dialogue thing you will need to create a new form and call it when you want. Also as u mentioned you are i will recommend watching this tutorial. I know it is outdated but it covers most of your doubts. I started with it and I think so should you.
Also I don't think a multiple line textbox is the best choice when you want to make a terminal like structure. Hope I cleared most of your doubts.
I've read answer here.
Cause problem is already found. As text change event is being fired on every change of Textbox's text change.
Two good working suggestion here mentioned,
To use exclusive Button and perform logic on Button's click
To use Textbox's Lost Focus event.
Both approach require user to leave Textbox ultimately. (so he would need to re-enter in terminal (textbox) if he wants to enter another command.
But here I wonder why nobody have suggested to track Enter press and do the logic only if Enter key being hit. Here user will not have to leave terminal (textbox) and fire another command without much effort.
you can do it like below.
First, use Textbox's key Up event, it will be fired later then Key Down (so to be sure that input is properly entered in textbox)
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
answer = textBox1.Text;
if (answer == "help")
{
MessageBox.Show("There is only 2 commands as of now and that is 'help' and 'program_speech' ");
}
else if (answer == "program_speech")
{
MessageBox.Show("Still currently under creation");
}
else
{
MessageBox.Show("Invalid Command. Please try again or type help for current available commands");
}
}
}
Alright,
I think I've found the problem.
The string variable named "answer", is it where the command entered by the user should be stored ?
Because in your code, nothing mentions it,
so try to add this line at the beginning of text_changed void :
answer = textBox1.Text;
If you're new to C#, this means you take the property Text of textBox1 and you store it in answer.
Hope it works !
You have to make sure, you are initializing the value of answer variable with the value of TextBox and change the event from TextChanged to LostFocus
private void textBox1_LostFocus(object sender, EventArgs e)
{
answer = textBox1.Text;
if (answer == "help")
{
MessageBox.Show("There is only 2 commands as of now and that is 'help' and 'program_speech' ");
}
else if (answer == "program_speech")
{
MessageBox.Show("Still currently under creation");
}
else
{
MessageBox.Show("Invalid Command. Please try again or type help for current available commands");
}
}
Related
I have a winforms program containing a RichTextBox.
The user inputs the text into the RichTextBox.
I wish to receive the input through keyboard events and not through textBox1.Text property, validate the string and only display it in the RichTextBox later.
How can I prevent the RichTextBox from displaying the input text by the user, even though the user inputs the text into the RichTextBox?
The RichTextBox is selected and has focus.
I am sorry. I just wanted to simplify the issue and therefore I neglected to mention that it is not a TextBox but a RichTextBox. It turns out that it matters, as the proposed solution is based on the PassowrdChar property, which is not natively supported by RichTextBox. I do not wish to create an inherited class for a property which is not even being used as such, only to suppress displaying the user input at input time.
You can actually use the KeyDown event. By doing that, you have an ability to validate the user input.
Tutorial
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
//
// Detect the KeyEventArg's key enumerated constant.
//
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("You pressed enter! Good job!");
}
else if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("You pressed escape! What's wrong?");
}
}
With that said, you have to store user input in string variable, validate it through the event and only then set variable value in textbox.
You can use this:
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
// ..
// handle the character as needed
// ..
e.Handled = true; // suppress the RTB from receiving it
}
Note that you may or may not want to treat mouse events like right mouseclicks to control inserting via the mouse..
I have a block of c# code on a TextChanged event for a winform textbox. Several of the voids called have messageboxes attached to them so the operator knows if they have valid data. Unfortunately, these calls get skipped completely. I have called the form in question with show() instead of showdialog() to eliminate the form being modal. Still no soap. The event is triggered by a barcode scanner. Code is as follows:
private void txtScanCode_TextChanged(object sender, EventArgs e)
{
string barCode;
barCode = txtScanCode.Text;
if (txtScanCode.Text.Length == 12)
{
MessageBox.Show(this, "Hey, look!", "A message box!",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
FindScanItem(barCode);
barCode = "";
txtScanCode.SelectionStart = 0;
txtScanCode.SelectionLength = txtScanCode.Text.Length;
}
}
I suspect it's a combination of text changed and keypress, but not really sure how it should be triggered properly.
After a week and a half, I have the answer, tested and verified. TaW and BillRuhl were on the right track with Leave and KeyPress. When those did not work, I finally hit on the KeyUp event.
A little background. A generic keyboard wedge USB scanner automatically adds a carriage return that trimming "\r\n" or Environment.Newline() will not get rid of. After several tries using different combinations and keypress, I caught the app firing a form before closing it. The barcode scanner, unlike normal keyboard input or cutting and pasting, continues to send an enter key to anything that listens for it during an event. I know. Buggy. But if we fire on the keyup event instead, like so...
private void txtScanCode_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
barCode = txtScanCode.Text.Trim().ToString();
if (!doDataStuff) //This boolean is instantiated as false
{
if (txtScanCode.Text.Length == 12)
{
doDataStuff = true; //boolean tells the app go run data functions.
MessageBox.Show(this, "Pop up worked!", "Cool!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
getData(barCode); //Data methods performed on the barcode
barCode = "";
txtScanCode.Focus();
txtScanCode.SelectionStart = 0;
txtScanCode.SelectionLength = txtScanCode.Text.Length;
}
}
}
}
...We look only for an enter key, validate on the length of the string (In this case, "==12" is essential for validation), and use KeyEventArgs to filter out Keys.Enter. Works perfectly with one caveat. KeyUp actually works on the form level, so it will fire on other text boxes as well. In this case, txtScanCode is the only one that has data-bound functions behind it, so all the validation is written to check against that control.
Thanks all for chiming in. I think we broke Google a couple of times trying to figure it out.
I just did a copy/paste test, and I think the problem may be in your if condition. If I copy more than 12 characters and paste it into the text box, the 'if' statement doesn't trigger.
This simple change seemed to fix that case:
if (textBox1.Text.Length >= 12)
{
MessageBox.Show(this, "Hey, look!", "A message box!",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
// the rest of your code here
// (you may want to do some additional validation
// on the text if it's more than 12 characters)
}
Try a different event...I have better luck with the Leave event than I do with the TextChanged event. So your method would look like:
private void txtScanCode_Leave(object sender, EventArgs e)
{
string barCode;
barCode = txtScanCode.Text;
if (txtScanCode.Text.Length == 12)
{
MessageBox.Show(this, "Hey, look!", "A message box!",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
FindScanItem(barCode);
barCode = "";
txtScanCode.SelectionStart = 0;
txtScanCode.SelectionLength = txtScanCode.Text.Length;
}
}
Don't forget to wire up the Leave event...
Hope that helps
Bill
Just put MessageBox.Show("ble"); and then MessageBox.Show("blu); and the "blu" will fire.
I am working on a unit converting project. The idea is to develop something like google's converter, except it is in windows application form.
I want the result to show based on user's input at the moment. that means if user is converting 100cm to m, the result will show 0.01m when 1 is typed in and 1m as he completes the input.
Is there a way to doing it? I have been searching in google but all of the helps are on java script.
Thanks!
You're looking for the KeyUp event.
Using textchanged event.In this example textbox1 is cm and textbox2 is m:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length == 0)
textBox2.Text = "0";
else
textBox2.Text = (double.Parse(textBox1.Text) / 100).ToString();
}
I want to write a simple text to speech program.
First, I want to make the program play only the written symbol. For example, if I type 'a' I want the program to say 'a' (I have recorded all of them), so when I type a word, it should spell it.
However, I am a beginner in C# and .Net and don't how to make the program understand the text I type. For example, in java I heard that there is a keyListener class, but I don't know which class should I use. I looked on MSDN but couldn't find it.
Which class or function should I use to listen to typed keys?
I suppose you are planning to use Windows Forms to achieve this.
The solution would be pretty simple. These events include MouseDown, MouseUp, MouseMove, MouseEnter, MouseLeave, MouseHover, KeyPress, KeyDown, and KeyUp. Each control has these events exposed. You just need to subscribe to it.
Please refer to this
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx
There would be a little bit of logic to find whether a complete word has been typed or not. A simple soultion would be , when space has been pressed, you can assume a word has been completed. Its very crude logic, as the user may have typed in wrong spelling and want hit backspace and correct the spelling. You may want to add lag to it.
If you are using Visual Studio like every other C# developer here is a more detailed code example:
Create a Windows Form and go to the [Design].
Select its properties (RMB=>properties), navigate to Events and double click LMB on KeyDown
VS will create and bind the event for you
Handle the KeyEventArgs depending on its value.
Example:
private void NewDialog_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.A:
{
MethodToOutputSound(AEnum);
break;
}
case Keys.B:
{
MethodToOutputSound(BEnum);
break;
}
case Keys.F11:
{
DifferentMethod();
break;
}
case Keys.Escape:
{
this.Close();
break;
}
default:
{
break;
}
}
}
Or use a lot of ifs
private void NewDialog_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyData == Keys.A)
{
MethodToOutputSound(AEnum);
}
if(e.KeyData == Keys.B)
{
MethodToOutputSound(BEnum);
}
...
}
Create a Windows Form with a TextBox in it. Handle the KeyPress event - that will give you the actual character that the user types. KeyDown and KeyUp won't help you.
You need to check the KeyChar property. Like this:
void MyEventHandler(object sender, KeyPressEventArgs e) {
// Do stuff depending on the value of e.KeyChar
}
private void button1_Click_1(object sender, EventArgs e)
{
string word = textBox1.Text;
foreach (char i in word)
{
switch (i)
{
case 'a':
case 'A': { // play sound a
break;
}
default:
{
// play no sound
break;
}
}
}
}
I just started programming with C# and I'm trying to get my windows form application to function properly. However, whenever I run it, it just opens up and closes immediately. Whenever I type similar code into Java, there's no problem with the GUI. Did I miss something small here?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form1_FormClosing();
}
private void Form1_FormClosing()
{
const string message =
"There's an updated version of this program available. Would you like to download now?";
const string caption = "Please update";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
MessageBox.Show("Program will close now. If you want to use this program please update to the newest version.", "Please update");
this.Close();
}
else if (result == DialogResult.Yes)
{
System.Diagnostics.Process.Start("http://www.google.com");
this.Close();
}
}
}
}
Don't call Form1_FormClosing(); within the Form1_Load. Not sure if you wanted that but both No and Yes will close the form. I suspect you have the Form1_Loadattached to theLoad` event of the form.
[Edit]
You comment that the message box is shown which will happen cause it is being displayed within the Load of the form. The form has not had a change to render itself.
What you're doing here is showing a message to the user telling him/her that a new version of the application is available.
Now, what choise does he/she have?
If the answer is no: You close the application
If the answer is yes: You close it too
That's exactly what you're doing here.
Please, make your question more clear so we can help you.
Try changing call MessageBox.Show(message, caption, ... to MessageBox.Show(this, message, caption, ... - that would make the message box modal to the form. Another thing to check is how you are showing your form - are you using default Main method generated by VS or have u made any changes to it?
You can try something of this sort
DialogResult result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly);
If you want to end the application in Form_Load(). Use FormClosing() event of Form, and call this.Close();.
EXAMPLE:
private void Form1_Load(object sender, EventArgs e)
{
this.Close(); //this will call Form_Closing()
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//do stuff
if (result == DialogResult.No)
{
e.Cancel = true; // if you don't want to close your form
}
else
{
// do stuff on closing form
}
}
What exactly is the problem??? Do you mean to say you are not able to view the message box itself or just the contents in it??
If the message box itself is not shown, then it means the Form1_Load event is not getting called properly. Try deleting the event and create it again by right clicking on the form ->Properties. In the event tab, click Load and then call the Form1_FormClosing method again inside the Load event.
Tried executing in my system and the form is working as expected.