c# Listbox control (arrows and enter keys) - c#

I have a listbox which displays the contents of an array. The array is populated with a list of results when my "go" button is pressed.
The go button is set as the AcceptButton on the form properties so pressing the Enter key anywhere in the focus of the form re-runs the go button process.
Double clicking on a result from the array within the listbox works fine using below:
void ListBox1_DoubleClick(object sender, EventArgs e) {}
I would like to be able to use my arrow keys and enter keys to select and run an event without having to double click on the line within the listbox. (however go button runs each time instead)
Basically open the form, type search string, press enter to run go button, use up and down arrows then press enter on selection to run same event as double click above. Will need to change focus after each bit.

You can handle the KeyDown events for the controls you want to override. For example,
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//execute go button method
GoButtonMethod();
//or if it's an event handler (should be a method)
GoButton_Click(null,null);
}
}
That will perform the search. You can then focus your listbox
myListBox.Focus();
//you might need to select one value to allow arrow keys
myListBox.SelectedIndex = 0;
You can handle the Enter button in the ListBox the same way as the TextBox above and call the DoubleClick event.

This problem is similar to -
Pressing Enter Key will Add the Selected Item From ListBox to RichTextBox
Certain controls do not recognize some keys when they are pressed in Control::KeyDown event. For e.g. list box does not recognize if the key pressed is Enter key.
See the remarks section of the Control::KeyDown event reference.
One way to resolve your problem might be writing a method for the Control::PreviewKeyDown event for your list box control:
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up && this.listBox1.SelectedIndex - 1 > -1)
{
//listBox1.SelectedIndex--;
}
if (e.KeyCode == Keys.Down && this.listBox1.SelectedIndex + 1 < this.listBox1.Items.Count)
{
//listBox1.SelectedIndex++;
}
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;
}
}

Related

MessageBox does not suppress keyboard Enter key

I have a button which, on Click event I made some validations upon some TextBoxes in my Form.
If a TextBox does not pass the validation, then I force the Focus to it (user must enter some characters in that TextBox). My TextBox class already have some code to go to the next control if user will press Enter key.
MyTextBox.cs class
public class MyTextBox : TextBox
{
public MyTextBox(){
KeyUp += MyTextBox_KeyUp;
KeyDown += MyTextBox_KeyDown;
}
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// This will suppress Blink sound
e.SuppressKeyPress = true;
}
}
private void MyTextBox_KeyUp(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
{
// This will go to the next control if Enter will be pressed.
SendKeys.Send("{TAB}");
}
}
}
Form's button click event:
private void BtnPrint_Click(object sender, EventArgs e){
// txtName is based on MyTextBox class
if(txtName.Text.Length == 0){
MessageBox.Show("Name field could not be empty! Please fill the Name!", "Error Message",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// If I Click the OK button, txtName will stay focused in the next line,
// but if I press Enter key, it will go to the next control.
txtName.Focus();
return;
}
// Some other validations ...
// Calling printing method ...
}
How do I stop the loosing focus on my textboxes when user hit Enter key in that MessageBox?
A MessageBox can cause re-entrancy problems in some occasions. This is a classic one.
In this specific case, when the Enter key is pressed to send a confirmation to the dialog, the KeyUp event re-enters the message loop and is dispatched to the active control. The TextBox, here, because of this call: txtName.Focus();.
When this happens, the code in the TextBox's KeyUp event handler is triggered again, causing a SendKeys.Send("{TAB}");.
There are different ways to solve this. In this case, just use the TextBox.KeyDown event to both suppress the Enter key and move the focus:
private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
SendKeys.Send("{TAB}");
}
}
Also, see (for example):
Pushing Enter in MessageBox triggers control KeyUp Event
MessageBox causes key handler to ignore SurpressKeyPress
as different methods to handle similar situations.

Need to trigger the button using only mouse click or alt + the hot key used for it in windows form

My problem
I have few buttons in a form. I need to trigger those button on mouse click or the alt + the alphabet used as the hot key in it.
I added & in front of the alphabet in the name property of the button. But my problem is that even if the alphabet is pressed without the use of alt key the below action is triggered.
The below is the method which triggers the button named FirstMatch.
public void firstMatch_Button_Click(object sender, EventArgs e)
{
Action_Raised(sender, "First Match");
}
First you need added & in front of the alphabet in the Text property not Name property of the button.
What you want to do is achieve by following code.
private void button1_Click(object sender, EventArgs e)
{
if (ModifierKeys.HasFlag(Keys.Alt) || e.GetType() == typeof(MouseEventArgs))
{
MessageBox.Show("button is clicked.");
}
}
You could change the property of your form KeyPreview to True
Now the form receives every key event first.
Then you can add an key up/down event to your form like this:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
// Replace "Keys.A" with the key you want
if (e.KeyCode == Keys.A && e.Alt)
{
this.firstMatch_Button.PerformClick();
}
}
And please remove the & otherwise the button gets further triggered.

control what the enter key does in WPF

I have a RichTextBox that i am searching text in and I want to be able to control what the enter key does when text is selected. I am able to use this if test below to call the method that I want, but my issue is after the method gets hit when the enter key is pressed it then moves the text to the second line and I want to be able to stop this from happening when the text is highlighted.
I test to check if the text is selected when enter is pressed.
if (IsTextSelected == true)
{
btnSearch_Click(sender, null);
}
You can listen to the PreviewKeyDown event like:
<RichTextBox PreviewKeyDown="RichTextBox_PreviewKeyDown"/>
and in the handler:
private void RichTextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
// DO YOUR WORK HERE and then set e.Handled to true on condition if you want to stop going to next line//
e.Handled = true;
}
}

TextBox.Keypress doesn't respond to return key

I have a form with various text boxes. One text box is used for entering a floating point number, so I am using TextBox.KeyPress to process each digit in turn, which only modifies the Text property. The text is processed by a routine that is called when the OK button id pressed (before closing the form). It is also called by the TextBox.Leave event. However, if I change the contents of the text box then press Return to variable isn't updated.
I thought I could overcome this by the following:
private void DestPointNoTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
prvUpdateDestPointNo();
}
}
This is called whenever a key is pressed while the text box is in focus, as can be proved by setting a breakpoint within it. However, it is not called when Return is pressed.
Can someone explain how I can ensure new text is processed when Return is pressed?
If I change the contents of one then click the OK button the new
I would use the Debugger to determine the value of e.KeyCode at runtime.
Why?
When I ran similar code (Winforms TextBox, KeyDown registered), the value of e.KeyCode was
e.KeyCode = LButton | MButton | Back
Another property of KeyEventArgs you can use is KeyValue -
private void DestPointNoTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 13)
{
prvUpdateDestPointNo();
}
}
If you are using Windows Form Application, then you can set the AcceptButton property of the Form to the OK button and the Click event of the OK button will be fired when you press Enter/Return key

Determining the type of Event that was raised on List Box, Selected Index Change. C#

I understand that there are Listbox Select index change questions floating around. However, this question focuses on a different matter. I have a list box, with some strings on the form. What I am trying to accomplish is to be able to scroll through the items in the list box (i.e using the arrow keys to navigate to a particular item). Once I navigate to the item I want, I want to either be able to press enter on the item and continue my application. So, the question is How to determine the Event type of that was raised on the List box in order to compare the event with either a Mouse Click event or a Keydown event, thus allowing me to decide which conditional statement to execute based of the result of the boolean expression......The reason I need to determine the type is because if the user presses ENter on the selectedIndexed Item a Dialogbox Appears, currently the dialogbox appears everytime a user HIGHLIGHTS a new item (you can see how that is a problem).
Psuedo Code
if (Listbox_Selected_Event_EventType isEqualTo Mouse_Click)
{
// execute code
} else if (Listbox_Selected_Event_EventType isEqualTo KeydownEvent)
{
// execute code
}
Finished code thanks to Evan,
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
if (e.KeyChar == (char)Keys.Return)
{
var file = Directory.GetFiles(urlHistoryFolder, listBox1.Text).FirstOrDefault();
String line;
try
{
using (StreamReader sr = new StreamReader(file))
{
line = sr.ReadToEnd();
}
DialogResult result1 = MessageBox.Show("Are You sure you want to Load this WebService", "Important Question", MessageBoxButtons.YesNo);
if (result1 == DialogResult.Yes)
{
//MessageBox.Show("Loading WebService");
textEndPointUri.Text = line;
listBox1.Visible = false;
GetBtn_Click(sender, e);
}
}
catch (Exception exp)
{
Console.WriteLine("File could not be read:");
Console.WriteLine(exp.Message);
}
}
}
}
The problem is you are looking at the wrong event. You should be handling the MouseClick event and the KeyUp or KeyDown event on the list box.
private void listBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Get the selected item and do whatever you need to it
//Open your dialog box
}
}
private void listBox1_Click(object sender, MouseEventArgs e)
{
//Get the selected item and do whatever you need to it
//Open your dialog box
}
Then there is no need for a conditional as you have handled both the events individually. Make sure you remove your Dialog box code from the SelectedIndexChanged event.
EDIT:
SelectedIndexChanged fires every time you select and item in the ListBox Object. The box still stores an index even if you don't handle that event. So you can reference or manipulate the PROPERTY of SelectedIndex anywhere. If you handle the two above events, any time a user clicks an item or presses enter you check if there is a selected item:
if (listBox1.SelectedIndex != -1)
{
//Now we know you have an item selected
//Do some stuff
}
Add a Button to the Form and set the AcceptButton() Property of the FORM to that Button. Now when Enter is pressed the Button will fire. Display your dialog in the Button Click() handler. This has the added benefit that people can also click the Button instead of pressing Enter:
private void button1_Click(object sender, EventArgs e)
{
if (ListBox.SelectedIndex != -1)
{
// ... display the dialog ...
Console.WriteLine(ListBox.SelectedItem.ToString());
}
}
To identify if ENTER has been pressed:
private void listBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
// do something
}

Categories

Resources