C# Call a function when a second key is pressed - c#

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.

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

Prevent KeyDown event identify SendKeys

I want to make a program to simulate textentry if user press the keys "D1 - D0" and simulate some numbers if user pressed the function keys..
Here is the code I have tried.
if (e.KeyData == Keys.D1){
SendKeys.Send("simulate this text entry");
}
if (e.KeyData == Keys.F12){
SendKeys.Send("123");
}
But the problem is when I press the F12 button, the KeyDown event identify the first "1" as the "D1" key and sends both "123" and "simulate this text entry"
How can I prevent this problem ?
When you go to send the keys, you'd have to set a flag so you know to ignore the characters being sent. Additionally, you'd need to know when to turn the flag back on. This could be done by setting a variable to the length of the value being sent, and then incrementing a counter with each detected key. This isn't foolproof as the user could hit keys in rapid succession (or hold a key down) and you wouldn't know if the keypress was a result of user interaction or from your simulation.
Here's the basic idea:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool IgnoreKeys = false;
private int target = 0;
private int counter = 0;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (!IgnoreKeys)
{
if (e.KeyData == Keys.D1)
{
Send("simulate this text entry");
}
if (e.KeyData == Keys.F12)
{
Send("123");
}
}
else
{
counter++;
if (counter == target)
{
IgnoreKeys = false;
}
}
}
private void Send(string entry)
{
IgnoreKeys = true;
counter = 0;
target = entry.Length;
SendKeys.Send(entry);
}
}
The problem is that using SendKeys.Send( ... ) there is no way your program can tell the difference between your sent keys and the user's keyboard input.
When you send the keys "123" it is the same as if the user pressed the 1, 2, and 3 keys.
Because you're listening for the 1 key, that event fires and catches the '1' sent by sendkeys.
If possible, try to append text to the content you're trying to "simulate textentry" into and avoid sendkeys.
Otherwise consider making your number hotkeys alt/ctrl-combinations such as this:
if (e.Control && e.KeyCode == Keys.D1)
{
SendKeys.Send("simulate this text entry");
e.Handled = true;
}
That will prevent this event from being fired when you press F12 and send "123" (because ctrl is not pushed).
Finally solved the problem.. :) Here is the code.. Have to use "SendKeys.Flush()" in this task...
private bool IgnoreKeys = false;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyData == Keys.D1) && (!IgnoreKeys))
{
SendKeys.Send("Simulate this text" + "{ENTER}");
}
if (e.KeyData == Keys.F12)
{
IgnoreKeys = true;
SendKeys.Send("123");
SendKeys.Flush();
IgnoreKeys = false;
}
This prevents the KeyDown event considering "1" in the text "123" as the key "D1"
Idea is Idle_Mind's :) Thank you..

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

Selecting dynamically created listboxs items in C#

I dynamically created a Listbox and filled it with some items, Upon typing a dot in a Textbox i want to show the Listbox so that the user can select any item by using arrow keys .
I did everything up to this point. When the user types a dot in the Textbox, The Listbox gets shown, But the arrow keys wont select any items!
private void txtResults_KeyDown(object sender, KeyEventArgs e)
{
string[] words= ((TextBox)sender).Text.Split(' ');
string s = sampleWord.Text = words[words.Length - 1];
if (e.KeyCode == Keys.OemPeriod)
{
ShowPopUpList(s);
}
else if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)
{
lst.Focus();//doesnt work :-/
}
else
{
lst.Hide();
txtResults.Focus();
}
}
This is the code for creating the listbox on FormLoad()
private void CreateListBox()
{
lst = new ListBox();
lst.Size = new Size(70, 130);
lst.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
lst.KeyDown += lst_KeyDown;
lst.DoubleClick += lst_DoubleClick;
//adding some test input
lst.Items.Add("بسم");
lst.Items.Add("الله ");
lst.Items.Add("الرحمن ");
lst.Items.Add("الرحیم ");
lst.Items.Add("بنام ");
lst.Items.Add("خداوند ");
lst.Items.Add("بخشنده ");
lst.Items.Add("مهربان ");
lst.Items.Add("الهی شکرت ");
}
private void ShowListbox()
{
txtResults.SelectionStart = txtResults.Text.Length;
txtResults.SelectionLength = 0;
Point index = txtResults.GetPositionFromCharIndex(txtResults.SelectionStart-1);
lst.Location = new Point (index.X-50, index.Y+70);
this.Controls.Add(lst);
lst.BringToFront();
lst.Show();
}
In ShowPopUpList(s) the ShowListbox() method is called. nothing fancy about it!
Note:
I only need the list box to get focus when i use UP or DOWN arrow keys to explicitly select an item. unless then i need to be able to freely continue typing and dont lose focus to listbox.
Whats the way around doing it ?
Remove focus from the textbox keydown handler and place it here:
private void ShowPopUpList(string s)
{
//your initialization of the
//listbox here and after..
listBox1.Focus();
}
Another way:
if (e.KeyCode == Keys.OemPeriod)
{
ShowPopUpList(s);
listBox1.Focus();
}
The real big difference is it gets focus rightaway.with your old code would first check the keydown and on the second hit it would already contain the focus.
Final Edit:
If Listbox needs to get the focus on up/down arrow keys(and only with those keys):
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)
{
ShowPopUpList();
listBox1.Focus();
listBox1.SelectedIndex = 0;
}
This worked just fine and dandy for me :)
ListBox lb;
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Contains("."))
{
lb = new ListBox();
lb.Location = textBox1.Location;
this.Controls.Add(lb);
lb.Items.Add("Item 1");
lb.Items.Add("Item 2");
lb.Items.Add("Item 3");
lb.Show();
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
lb.Focus();
}
}

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