How can I get original character? - c#

I want to get a TextBox input key.
I was generate "KeyDown" event and
using the next
string inputKey = new KeysConverter().ConvertToString(e.KeyCode)
bun it is only assign upper case.
I want both upper case and lower case.
What should I do?

If you insist on using KeyDown Event This is what you need.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
string inputKey;
bool capsLock = IsKeyLocked(Keys.CapsLock); // Check for capslock is on
bool shift = e.Shift; // Check for Shift button was pressed
if ((shift && !capsLock) || (!shift && capsLock))
{
inputKey = new KeysConverter().ConvertToString(e.KeyCode);
}
else if ((shift && capsLock) || (!shift && !capsLock))
{
inputKey = new KeysConverter().ConvertToString(e.KeyCode).ToLower();
}
}

You should use the KeyPress event and then get the character with e.KeyChar.
For example:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}

Related

Textbox doesn't return current value in Visual C#

I'm trying to put the current integer value of a textbox immediately into an integer, but with following code it seems that I'm always 1 step behind :
private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
// Only allow numeric value
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
if (txtMemoryLocation.Text != "")
{
nLocation = int.Parse(txtMemoryLocation.Text.Trim());
}
}
I always start with a number 1 in the textbox, when I change the "1" to "10", my nLocation changes to 1, when I enter "100", nLocation becomes 10.
What is going on?
the KeyPress and KeyDown event will call before add new pressed char TextBox.Text and if e.handle is false the new char will add to TextBox.Text and TextBox.TextChanged will called. you can do this like me
Note : at first add TextChanged metod to txtMemoryLocation.TextChanged
private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar));
}
private void TextChanged(object sender,EventArgs e)
{
nLocation = int.Parse(txtMemoryLocation.Text.Trim());
}
Hook the TextChanged event instead and do your parsing there. When KeyDown, KeyPress, and KeyUp fire, the textbox still hasn't had a chance to accept the new character.
Alternatively you could including the newly pressed key my modifying your existing function like this:
private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
// Only allow numeric value
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
if (txtMemoryLocation.Text != "")
{
nLocation = int.Parse(txtMemoryLocation.Text.Trim() + e.KeyChar);
}
}

C# TextBox Auto Caps Lock On

I need the following code : When I press shift key then I write small letters in my TextBox in other case I write big letters something like a “reverse” or all time pressed Caps Lock Key.
So This code and other similar is helpless because there are only one kind of letter size :
textBox1.CharacterCasing = CharacterCasing.Upper;
textBox1.CharacterCasing = CharacterCasing.Lower;
Thanks for help !
The easiest option is to change the text in the TextChanged event method. After entering a character, change its layout. But you must remember that text can be pasted / cut.
If you ignore this problem, you can use this simple example:
public partial class Form1 : Form
{
int last_len = 0;
bool char_to_lower = false;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
// save last cursor position
var select_index = textBox1.SelectionStart;
// if text not delete - change char casing
if (textBox1.Text.Length > last_len && select_index > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append(textBox1.Text.Take(select_index - 1).ToArray());
// check SHIFT and CAPS
if (char_to_lower || Control.IsKeyLocked(Keys.CapsLock))
sb.Append(textBox1.Text[select_index - 1].ToString().ToLower());
else
sb.Append(textBox1.Text[select_index - 1].ToString().ToUpper());
sb.Append(textBox1.Text.Skip(select_index).ToArray());
// insert new text in textBox
textBox1.Text = sb.ToString();
// return cursor position
textBox1.SelectionStart = select_index;
}
// save last length
last_len = textBox1.Text.Length;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Shift) char_to_lower = true;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Shift) char_to_lower = false;
}
}

How to detect a custom key from Keyboard using C#

I have a USB Keyboard that have some Special keys like "FN",PLAY,MUTE and one that changes the keyboard light. I was trying to get what is this key "name" to perform a logic to change the color periodically.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var key = sender as TextBox;
var result = key.Text;
}
But the key its not a string to be recognized. How can I do this ? Thanks!
I will suggest you to use OnKeyPress and OnKeyDown events instead to check what was pressed. MSDN Link.
Example:
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if(e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift) {
nonNumberEntered = true;
}
}
// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
}
}

How to capture the spacebar press event using KeyeventHandler?

I have a Form with a rich text box in which i want to do the following:
When user presses the spacebar button (Currently i am doing it with keydown event but want to use key press event but it doesn't provide e.keycode), a function should be called in which this logic is to be implemented:
last written word is to be fetched and is to be looped through the text of rich text box in order to find its number of occurrences in a rich text box.
What i have done so far is:
private void textContainer_rtb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
String abc = this.textContainer_rtb.Text.Split(' ').Last();
chkWordRepeat(abc);
}
}
public void chkWordRepeat(String lastWordToFind)
{
int count = new Regex(lastWordToFind).Matches(this.textContainer_rtb.Text.Split(' ').ToString()).Count;
MessageBox.Show("Word: " + lastWordToFind + "has come: " + count + "times");
}
Please let me know if the above mentioned logic is correct or not And how can i attach this logic with key press event for spacebar? If not then please help me implementing!
Thanks in advance.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == ' ')
MessageBox.Show("space pressed");
}
My opinion is :
public Dictionary<string, int> data;
private void textContainer_rtb_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
String abc = this.textContainer_rtb.Text.Split(' ').Last();
chkWordRepeat(abc);
}
}
public void chkWordRepeat(string wrd)
{
bool present = false;
foreach (string key in data.Keys)
if (wrd == key)
{
present = true;
data[wrd]++;
}
if (!present)
data.Add(wrd, 1);
}

c# windows forms capital letters

My user can enter some text into the combobox but I wish that this text is automatically shown in capital letters (as if user had capslock on). Any ideas how to do this?
You will want to handle the KeyPress event.
private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 'a' && e.KeyChar <= 'z')
e.KeyChar -= (char)32;
}
32 is just the difference in ASCII values between lowercase and uppercase letters.
Here is how I handled it, it gives a much smoother change than simply replacing the whole text.
private void ComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetter(e.KeyChar))
{
int p = this.SelectionStart;
this.Text = this.Text.Insert(this.SelectionStart, Char.ToUpper(e.KeyChar).ToString());
this.SelectionStart = p + 1;
}
}
another example
private void TextBox_Validated(object sender, EventArgs e)
{
this.TextBox.Text = this.TextBox.Text.ToUpper();
}
Regards
You can register to the TextChanged event and convert the text to capitals.
private void combobox_TextChanged(object sender, EventArgs e)
{
string upper = combobox.Text.ToUpper();
if(upper != combobox.Text)
combobox.Text = upper;
}

Categories

Resources