How to capture the spacebar press event using KeyeventHandler? - c#

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

Related

How can I enter data to Textboxes sequentially

I'm a newbee to C# and I'm trying to write code in Visual Studio. I need your help.
I want to enter numbers to 20pcs textbox in tabpage1 in form by hand held barcode scanner in C#. Cursor must go to next textbox after reading from barcode scanner. And I will check the read data with some conditions (between 2 values numbers etc) for every textbox.
I write some code but it makes code size big. I think it must be easy way I need your comment and help.
The barcode scanner reads the barcode and sends barcode number + enter code. And barcode scanner read and put number to first textbox then pass to next textbox and it repeating for all textbox - how can I do this easily?
Thanks
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox1.SelectAll();
textBox2.Focus();
e.Handled = true;
}
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.SelectAll();
textBox3.Focus();
e.Handled = true;
}
}
.
.
.
.
private void textBox20_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox20.SelectAll();
textBox1.Focus();
e.Handled = true;
}
}
The good news is that the sender object is always that control which has triggered the event. In other words the sender is a reference to one of your TextBoxs.
You can take advantage of this fact and you can have a single event handler, which could be reused for multiple events.
private void textBoxN_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBoxCurrent = sender as TextBox;
textBoxCurrent.SelectAll();
//TODO: set focus for next
e.Handled = true;
}
}
So, the next question is how to get a reference to the next TextBox?
You can use the Tag property for this.
In case of WinForms the Control object has a property called Tag.
In case of WPF the FrameworkElement object has a property called Tag.
In both cases this property is an object so we can store anything in that. If we populate that with a reference to the next TextBox then the generic handler would look like this:
private void textBoxN_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textBoxCurrent = sender as TextBox;
textBoxCurrent.SelectAll();
var textBoxNext = textBoxCurrent.Tag as TextBox;
textBoxNext.Focus();
e.Handled = true;
}
}
What's left?
Populate the Tag properties
Subscribe to the KeyDown events
private void Init()
{
var textBoxes = new List<TextBox> { TextBox1, TextBox2, ..., TextBox20 };
foreach(var item in textBoxes.Select((textBox, index) => (textBox, index))
{
var nextIdx = (item.index + 1) % textBoxes.Count;
item.textBox.Tag = textBoxes[nextIdx];
item.textBox.KeyDown += textBoxN_KeyDown;
}
}
We have created an iterator here which is deconstructed into a textbox and an index of this TextBox in the textBoxes collection.
We have calculated the next TextBox index into the nextIdx. Then we have wired up everything.
here is an idea for solving
class Program
{
LinkedList<TextBox> _textBoxes;
ctor()
{
_textBoxes = new LinkedList<TextBox>();
_textBoxes.List.AddLast(textbox1);
_textBoxes.List.AddLast(textbox20);
}
private void textBox_KeyDown_justOneCommonHandle(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
var textboxCurrent = _textBoxes.Current;
// make sure that Value is the sender
textboxCurrent.SelectAll();
_textBoxes.MoveNext();
var textboxNext = _textBoxes.Current;
// check the end of list
textboxNext.Focus();
e.Handled = true;
}
}
}
# Peter Csala, #Ivan Stavenchuk
Thanks for your idea and help. I solved my problem as shown below
I added a main Textbox (textBox21) and used keydown event of main textbox
private void textBox21_KeyDown(object sender, KeyEventArgs e)
{
TextBox tb = new TextBox();
tb.Name = "textBox" + i.ToString();
if (e.KeyCode==Keys.Enter)
{
TextBox tbx = this.Controls.Find(tb.Name, true).FirstOrDefault() as TextBox;
tbx.Text = textBox21.Text ;
i++;
if (i>20) i=1;
textBox21.SelectAll();
}
}

C# Call a function when a second key is pressed

I'm lost calling a function when a second key is pressed. I have used KeyDown event for my buttons. And that KeyDown will call a function that will check that button. My problem is after checking that button, the user must press another Enter Key or Spacebar to go on the next data.
This is for my radiobutton1 KeyDown event
private void btn1_KeyDown(object sender, KeyEventArgs e)
{
btn1.BackColor = Color.Blue;
checkAns(btn1.Text, btn1);
}
This is my checkAns function that will check the selected button
private void checkAns (string ansText, RadioButton rdo)
{
var row = dTable.Rows[currentRow];
var ans = row["ANSWER"].ToString();
if (ansText == ans)
{
rdo.BackColor = Color.Green;
correctAdd();
//MessageBox.Show("Correct");
}
else
{
rdo.BackColor = Color.Red;
wrongAdd();
//MessageBox.Show("Wrong. Answer is" + " \n " + ans);
}
nextEnter (------); //Here I'm not sure how to call the another keydown/keypress event or value of the enter key
}
This is my nextEnter function
private void nextEnter(------) //Also at this part.
{
if (------ == Keys.Enter) //And here.
currentRow++;
currentNo++;
remain--;
nextRow();
}
i solve this problem by having the form increment a variable during enter keydown event.
private void frmTest_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Space)
{
entCount++;
}
}
and use if statement when entCount == 2, show the next data and reset the entCount to 0.
To demonstrate what I meant in my comment:
You could pass the KeyCode property of your KeyEventArgs from btn1_KeyDown
private void btn1_KeyDown (object sender, KeyEventArgs e)
{
btn1.BackColor = Color.Blue;
checkAns (btn1.Text, btn1, e.KeyCode);
}
to checkAns
private void checkAns (string ansText, RadioButton rdo, Keys pressedKey)
{
var row = dTable.Rows [currentRow];
var ans = row ["ANSWER"].ToString ();
if (ansText == ans)
{
rdo.BackColor = Color.Green;
correctAdd ();
//MessageBox.Show("Correct");
}
else
{
rdo.BackColor = Color.Red;
wrongAdd ();
//MessageBox.Show("Wrong. Answer is" + " \n " + ans);
}
nextEnter (pressedKey); //Here I'm not sure how to call the another keydown/keypress event or value of the enter key
}
And further on to nextEnter:
private void nextEnter (Keys key) //Also at this part.
{
if (key == Keys.Enter) //And here.
currentRow++;
currentNo++;
remain--;
nextRow ();
}
Tell me if I misunderstood anything, you need further help or my solution doesn't work for you.

How can I get original character?

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

Make code for multiple textbox when press Enter send command Tab better

i already have code when user press key Enter on keyboard, it return tab and "jump" to next field, its working great, its possible make it for 2 or 3 textbox, problem when need make it on multiple textbox like 20 textbox for each form, its just not work.
See code:
// Detect if Enter key is pressed on each text box, mute sound enter "ding" sound and replace Enter for tab (problem that have make it for each textbox)
private void txtAltura_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
private void txtLargura_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
private void txtProfundidade_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true; //Silenciar Enter
SendKeys.Send("{TAB}");
}
}
//execute keypress command when enter is typed on textbox
private void txtProfundidade_TextChanged(object sender, EventArgs e)
{
if (txtProfundidade.Text != "") { foreach (char c in txtProfundidade.Text.ToCharArray()) txtProfundidade_KeyPress(sender, new KeyPressEventArgs(c)); }
}
private void txtLargura_TextChanged(object sender, EventArgs e)
{
if (txtLargura.Text != "") { foreach (char c in txtLargura.Text.ToCharArray()) txtLargura_KeyPress(sender, new KeyPressEventArgs(c)); }
}
private void txtAltura_TextChanged(object sender, EventArgs e)
{
if (txtAltura.Text != ""){foreach (char c in txtAltura.Text.ToCharArray()) txtAltura_KeyPress(sender, new KeyPressEventArgs(c));}
}
Hope make it better.
Thanks in advance..
if its windows form app can use this, this will replace tab key press with Enter key
protected override bool ProcessKeyPreview(ref Message m)
{
if (m.Msg == 0x0100 && (int)m.WParam == 13)
{
this.ProcessTabKey(true);
}
return base.ProcessKeyPreview(ref m);
}
From what I understand, you're trying to figure out a way to assign event handlers to multiple textbox controls and don't want to write a handler for each one. If that's the case, try this:
private void Form1_Load(object sender, EventArgs e)
{
foreach (TextBox textBox in this.Controls.OfType<TextBox>())
{
textBox.KeyDown += new KeyEventHandler(textBox_KeyDown);
}
}
void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
SendKeys.Send("{TAB}");
}
}
This will assign a handler to each textbox control on the form.
That worked perfectly well.
I also have to repeat this on each textbox to check if all codes was filled and update statusbar:
private void txtAltura_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
private void txtLargura_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
private void txtProfundidade_TextChanged(object sender, EventArgs e)
{
testePreenchidoecalculo();
}
Its possible to make it better ?

Pressing Enter Key will Add the Selected Item From ListBox to RichTextBox

related to this topic:
Hidden ListBox will appear while Typing Words in RichTextBox
im working on a code editor and i just want to know if how can I add items from listbox to textbox using enterkey .
further more heres my strings:
public String[] ab = { "abstract" };
public String[] am = { "AmbientProperties", "AmbientValueAttribute" };
sample:
in richtextbox (rtb) , i type Ab, then hiddenlistbox will appear with "abstract" text on it (already do that) using this code:
if (token == "letterA" || token.StartsWith("Ab") || token.StartsWith("ab"))
{
int length = line.Length - (index - start);
string commentText = rtb.Text.Substring(index, length);
rtb.SelectionStart = index;
rtb.SelectionLength = length;
lb.Visible = true;
KeyWord keywordsHint = new KeyWord();
foreach (string str in keywordsHint.ab)
{
lb.Items.Add(str);
}
break;
}
then after that after i press enterkey i want to add the abstract from listbox to the richtextbox .
RichTextBox declared as rtb and ListBox declared as lb
what should i do? thanks .
Certain controls do not recognize some keys when they are pressed in key down event.
For eg ListBox do not recognize if key pressed is Enter Key.
Please see remarks section in following link -
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown(v=vs.110).aspx
one of the solution for your problem can be
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx
implement PreviewKeyDown Event for your listbox for listbox to recognize your actions.
Here is sample code snippet -
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Do your task here :)
}
}
private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Enter:
e.IsInputKey = true;
break;
}
}
You cannot directly type text to a listbox, so I created a example with textBox:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
this.richTextBox1.AppendText((sender as TextBox).Text);
e.Handled = true;
}
}
If you meant comboBox you can easily adjust this, replace line above:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
this.richTextBox1.AppendText((sender as ComboBox).Text);
e.Handled = true;
}
}
Copy selected listbox entries to rtf box:
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
foreach (string s in listBox1.SelectedItems)
{
this.richTextBox1.AppendText(s + Environment.NewLine);
}
e.Handled = true;
}
}

Categories

Resources