I have a question about a small practice program I'm working on. I have almost no experience with C#, and a little bit of experience with Visual Basic. The problem I'm having has to do with only allowing numbers in the text box. I succeeded in doing so in another program, but for some reason it isn't working with relatively the same code.
Here is the code:
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 btnCalculate_Click(object sender, EventArgs e)
{
Double TextBoxValue;
TextBoxValue = Convert.ToDouble(txtMinutes.Text);
TextBoxValue = Double.Parse(txtMinutes.Text);
{
Double Answer;
if (TextBoxValue > 59.99)
{
Answer = TextBoxValue / 60;
}
else
{
Answer = 0;
}
{
lblAnswer.Text = Answer.ToString();
}
}
}
private void txtHours_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber (e.KeyChar) && Char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
}
}
If there are other errors in my code that anyone here can correct me on, that is also appreciated. Thanks in advance.
You've got the checks inverted. What your code does is to cancel input if the new character is a number AND if it's a control character.
if (!char.IsNumber(e.KeyChar) && !Char.IsControl(e.KeyChar))
e.Handled = true;
Your logic is incorrect. It states "if the pressed key is a number and a control character.. then i've handled it". What you want is "if the pressed key is NOT a number, I've handled it".
if (!char.IsNumber(e.KeyChar)) {
// ...
private void txtHours_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
e.Handled = true;
// only allow one decimal point
if (e.KeyChar == '.'
&& (txtHours).Text.IndexOf('.') > -1)
e.Handled = true;
}
Related
I am new to c#. I am learning graphic objects by doing a Hangman game.
I need to save two char arrays : first from the word to be searched in word_selection_proposal(), second from the word suggested by the other player in word_selection_analysis().
I was thinking in using a boolean variable named first to ensure if that is the first time the function txtWord_KeyPress is called or not, to distinguish the first ENTER from the first player to the player who is searching for the word. I understand my boolean is a local variable so it is reset to true each time ENTER is pressed.
Is there a possibility to count the number of times ENTER is pressed so then I can distinguish which function to call to save the arrays then I could save this data.
Please, see just below the code and a picture to understand the code.
Thank you in advance
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 Hangman_Game
{
public partial class Hangman : Form
{
public Hangman()
{
InitializeComponent();
}
private void Hangman_Load(object sender, EventArgs e)
{
FillComboLetters();
comboLetters.Enabled = false;
btnTest.Enabled = false;
btnReplay.Enabled = false;
lblVictory.Text = "";
txtWord.Text = "Enter a word to search here";
txtWord.Focus();
}
private void FillComboLetters()
{
comboLetters.Items.Clear();
for (int k = 0; k < 26; k++)
{
comboLetters.Items.Add((char)('A' + k));
}
comboLetters.SelectedIndex = 0;
}
private void txtWord_Click(object sender, EventArgs e)
{
txtWord.Text = "";
txtWord.Focus();
}
private void txtWord_KeyPress(object sender, KeyPressEventArgs e)
{
Boolean first = true;
string message = txtWord.Text.ToUpper();
if ((e.KeyChar == (char) Keys.Enter) && first)
{
word_selection_proposal(message);
first = false;
}
if ((e.KeyChar == (char)Keys.Enter) && !first)
{
word_selection_analysis(message);
}
}
private void word_selection_proposal(string word)
{
char[] player1 = word.ToCharArray();
txtWord.Text = "Array copied, Now your turn";
}
private void word_selection_analysis(string word)
{
char[] player2 = word.ToCharArray();
txtWord.Text = "array copied";
txtWord.Focus();
}
}
}
I have a primitive app with 2 comboBoxes. They work fine after first starting the app.
However after typing in text in the search bar and pressing enter, the comboboxes loop their contents.
It happens after I type in the textbox, even if I do not press enter. Every time I press a key another repeat list of options appends to the comboBox.
How do I prevent this comboBox malfunction? Here is my code.
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;
//Nick Knapp
//CSCI 363 Fall 2019
namespace c363_hw3_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "Library Literature Search";
this.BackColor = Color.White;
comboBox2.Items.Add("All");
comboBox2.Items.Add("Books");
comboBox2.Items.Add("Papers");
comboBox2.Items.Add("Films");
comboBox2.Items.Add("CDs");
comboBox2.Items.Add("Other");
comboBox2.SelectedIndex = 0;
comboBox1.Items.Add("Title");
comboBox1.Items.Add("Author");
comboBox1.Items.Add("Publisher");
comboBox1.Items.Add("ISBN");
comboBox1.SelectedIndex = 0;
// this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckEnter);
//this.Controls.Add(textBox1);
this.ActiveControl = textBox1;
textBox1.KeyPress += new KeyPressEventHandler(keypressed);
}
private void keypressed(Object o, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
textBox1.Text = "";
e.Handled = true;
}
}
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
I think your code is correct but have you ever tried these 2 method after calling combo boxes?
comboBox1.ResetText();
comboBox1.Items.Clear();```
i think it works
private void keypressed(Object o, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
textBox1.Text = "";
comboBox1.Items.Clear();
e.Handled = true;
}
}
I am currently in need of a multi-line textbox that can do suggest/append of the desired list items so far I am able to get the suggestion but the only problem is now is that it is working abnormally, i.e. showing suggestion for white spaces, when I press enter in order to autocomplete it gives me multiple strings of that characters, also there is a problem that due to my logic it only show suggestion to the strings that are at the end of the textbox, not the one that is inserted in between.
So far my code is following
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 multiline_text_suggest
{
public partial class Form1 : Form
{
ListBox listBox = new ListBox();
public Form1()
{
InitializeComponent();
Controls.Add(listBox);
listBox.Hide();
textsplit();
}
string intellisenes;
private void textsplit() {
listBox1.Items.Clear();
foreach (string c in textBox.Text.Split()) {
listBox1.Items.Add(c);
}
intellisenes = listBox1.Items[listBox1.Items.Count-1].ToString().Trim();
}
void listBox_SelectedIndexChanged(object sender, KeyEventArgs e)
{
if (e.KeyValue == (decimal)Keys.Enter)
{
textBox.Text += ((ListBox)sender).SelectedItem.ToString();
textBox.Focus();
listBox.Hide();
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
textsplit();
listBox.SetBounds(textBox.Left, textBox.Top + textBox.Height, textBox.Width + 20, 40);
listBox.KeyDown += listBox_SelectedIndexChanged;
List<string> list = new List<string>(){"king","kong"};
var localList = list.Where(z => z.StartsWith(intellisenes.Trim())).ToList();
if (localList.Any() && !string.IsNullOrEmpty(textBox.Text) && !string.IsNullOrWhiteSpace(textBox.Text))
{
listBox.DataSource = localList;
listBox.Show();
listBox.Focus();
}
}
private void textBox_TextChanged(object sender, EventArgs e)
{
textsplit();
}
}
}
Forgive me for any mistakes since I am just a noob in coding.
I have two quick question about this simple calculator application I am trying to build in C#. (not homework by the way) I am trying to get the MessageBox.Show message to show in the multiply and add sections of my code, but they don't seem to be displaying even if I enter a negative value. The application just seems to do the math anyways. Also, this may be a dumb one, how do I get rid of the label5 text that appears in the application with out deleting it in the properties window?
Any help will be greatly appreciated, thanks!
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 AddMultiply
{
public partial class AddMultiply : Form
{
public AddMultiply()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void txtFirstValue_TextChanged(object sender, EventArgs e)
{
}
private void btnAdd_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
while (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
while(double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue + secondValue;
lblAnswer.Text = answer.ToString();
}
private void btnMultiply_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
while (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
while (double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue * secondValue;
lblAnswer.Text = answer.ToString();
}
private void lblAnswer_Click(object sender, EventArgs e)
{
lblAnswer.Text = ""; //tries to get rid of "label5" text in application, but fails to do so
}
}
}
1)you should change the while to "if":
private void btnAdd_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
if (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
if(double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue + secondValue;
lblAnswer.Text = answer.ToString();
}
2) where is Ladel5 ? It doesn't seem to be exist...
You can try the following code to show the MessageBox then the value is less than 0:
if (n1 < 0 || n2 < 0)
MessageBox.Show("Value less than ZERO ", "Value less than ZERO",MessageBoxButtons.OK , MessageBoxIcon.Exclamation);
As for getting rid of the label you can try :
label5.Visible = false;
I'm using global keyboard hooks as a keyboard listener when the window is out of focus. I'm half way through some code and I realise that for whatever reason, putting caps lock on changes the output of KeyEventArgs. Using shift/no shift outputs ordinary results but if I were to put caps lock on, A will become U, B will become V, C will become W and so on. Here's a look at the code that does this (will add global keyboard hooks if necessary):
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;
using Utilities;
namespace WindowsFormsApplication1
{
public partial class Form6 : Form
{
globalKeyboardHook gkh = new globalKeyboardHook();
int sign_Indicator = 0;
double variable1;
double variable2;
int addBit = 0;
int subBit = 0;
int multBit = 0;
int divBit = 0;
int modBit = 0;
Boolean fl = false;
String s, x;
public Form6()
{
InitializeComponent();
}
private void Form6_Load(object sender, EventArgs e)
{
gkh.HookedKeys.Add(Keys.A);
gkh.HookedKeys.Add(Keys.B);
gkh.HookedKeys.Add(Keys.C);
gkh.HookedKeys.Add(Keys.D);
gkh.HookedKeys.Add(Keys.E);
gkh.HookedKeys.Add(Keys.F);
gkh.HookedKeys.Add(Keys.G);
gkh.HookedKeys.Add(Keys.H);
gkh.HookedKeys.Add(Keys.I);
gkh.HookedKeys.Add(Keys.J);
gkh.HookedKeys.Add(Keys.K);
gkh.HookedKeys.Add(Keys.L);
gkh.HookedKeys.Add(Keys.M);
gkh.HookedKeys.Add(Keys.N);
gkh.HookedKeys.Add(Keys.O);
gkh.HookedKeys.Add(Keys.P);
gkh.HookedKeys.Add(Keys.Q);
gkh.HookedKeys.Add(Keys.R);
gkh.HookedKeys.Add(Keys.S);
gkh.HookedKeys.Add(Keys.T);
gkh.HookedKeys.Add(Keys.U);
gkh.HookedKeys.Add(Keys.V);
gkh.HookedKeys.Add(Keys.W);
gkh.HookedKeys.Add(Keys.X);
gkh.HookedKeys.Add(Keys.Y);
gkh.HookedKeys.Add(Keys.Z);
gkh.HookedKeys.Add(Keys.D1);
gkh.HookedKeys.Add(Keys.D2);
gkh.HookedKeys.Add(Keys.D3);
gkh.HookedKeys.Add(Keys.D4);
gkh.HookedKeys.Add(Keys.D5);
gkh.HookedKeys.Add(Keys.D6);
gkh.HookedKeys.Add(Keys.D7);
gkh.HookedKeys.Add(Keys.D8);
gkh.HookedKeys.Add(Keys.D9);
gkh.HookedKeys.Add(Keys.D0);
gkh.HookedKeys.Add(Keys.Return);
gkh.HookedKeys.Add(Keys.Shift);
gkh.HookedKeys.Add(Keys.CapsLock);
gkh.HookedKeys.Add(Keys.Back);
gkh.HookedKeys.Add(Keys.Escape);
gkh.HookedKeys.Add(Keys.Space);
gkh.HookedKeys.Add(Keys.OemPeriod);
gkh.HookedKeys.Add(Keys.Oemcomma);
gkh.HookedKeys.Add(Keys.OemMinus);
gkh.HookedKeys.Add(Keys.Oemplus);
gkh.HookedKeys.Add(Keys.OemPipe);
gkh.HookedKeys.Add(Keys.OemBackslash);
gkh.HookedKeys.Add(Keys.OemOpenBrackets);
gkh.HookedKeys.Add(Keys.OemCloseBrackets);
gkh.HookedKeys.Add(Keys.OemQuotes);
gkh.HookedKeys.Add(Keys.OemSemicolon);
gkh.HookedKeys.Add(Keys.Oemtilde);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
}
public static string location = "C:\\Users\\Hayden\\Desktop\\log.txt";
void gkh_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Shift)
{
if (e.KeyCode == Keys.OemPipe)
{
System.IO.File.AppendAllText(#location, "|");
}
else
{
System.IO.File.AppendAllText(#location, e.KeyCode.ToString());
}
}
else
{
if (e.KeyCode == Keys.Return)
{
System.IO.File.AppendAllText(#location, "[RETURN]");
}
else if (e.KeyCode == Keys.Back)
{
System.IO.File.AppendAllText(#location, "[BACKSPACE]");
}
else if (e.KeyCode == Keys.Space)
{
System.IO.File.AppendAllText(#location, " ");
}
else if (e.KeyCode == Keys.OemPeriod)
{
System.IO.File.AppendAllText(#location, ".");
}
else if (e.KeyCode == Keys.Oemcomma)
{
System.IO.File.AppendAllText(#location, ",");
}
else if (e.KeyCode == Keys.OemPipe)
{
System.IO.File.AppendAllText(#location, "\\");
}
else if (e.KeyCode == Keys.CapsLock)
{
System.IO.File.AppendAllText(#location, "");
}
else if (Control.IsKeyLocked(Keys.CapsLock))
{
System.IO.File.AppendAllText(#location, e.KeyCode.ToString());
}
else
{
System.IO.File.AppendAllText(#location, e.KeyCode.ToString().ToLower());
}
}
}
How can I fix this? I have no idea why it's changing the letter completely just because I put caps lock on. Shift works fine though.
The globalKeyboardHook class you link to has a AddModifiers(Keys key) method with this line:
if ((GetKeyState(VK_CAPITAL) & 0x0001) != 0) key = key | Keys.CapsLock;
This code checks if Cap Lock is on and if so it ORs the key variable which is later returned by the method.
The problem is that Caps Lock is not a modifier key and shouldn't be manipulated this way. This is the reason you're seeing the strange key values you are when Caps Lock in on.
Incidentally, only Control, Shift and Alt are modifier keys and AddModifiers() handles these.
If you remove this line I believe you'll be fine.