control what the enter key does in WPF - c#

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

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.

Interpret Enter as Tab with selection

I use this code on Enter keypress to move focus to next like the Tab does in a datagrid.
uiElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
At the end of any row while hitting enter moves the focus to the next line but the selection stays where it was. On the other hand using Tab brings the selection with the focus.
Is there a way to move the selection aswell with some adjustments?
Matt Hamilton's answer is great but not doing the selection.
What you could do, instead of trying to programmatically switch focus, is simulating a tab key press each time the enter key is pressed inside the DataGrid. It would then look something like this:
private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
var dataGrid = (DataGrid)sender;
var keyEventArgs = new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(dataGrid), 0, Key.Tab)
{
RoutedEvent = Keyboard.KeyDownEvent,
};
dataGrid.RaiseEvent(keyEventArgs);
e.Handled = true;
}
}

How to make TextBox handle text like a hyperterminal in c#?

When the user enters a character with the TextBox in focus, I do not want the character to show up on the TextBox at all and I don't want to use the Clear() method as there may be other text in the TextBox I don't want erased. so far I've tried:
private void WriteBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // enter key pressed
{
WriteBox1.Text = "";
}
// Code to write Serial....
String writeValues = WriteBox1.Text;
String withoutLast = writeValues.Substring(0, 1);
WriteBox1.Text = withoutLast;
}
This leaves the last letter entered in writeBox1. I need it to delete all characters entered.
I've also tired:
writeValues.Replace(writeValues, "");
WriteBox1.Text = writeValues;
Try setting Handled property on eventargs. Set Handled to true to cancel the KeyPress event. This keeps the control from processing the key press.
example :
private void keypressed(Object o, KeyPressEventArgs e)
{
// The keypressed method uses the KeyChar property to check
// whether the ENTER key is pressed.
// If the ENTER key is pressed, the Handled property is set to true,
// to indicate the event is handled.
if (e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
}
}
https://msdn.microsoft.com/ru-ru/library/system.windows.forms.keypresseventargs.handled%28v=vs.110%29.aspx

c# Listbox control (arrows and enter keys)

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

C# KeyEvent doesn't log the enter/return key

I've been making this login form in C# and I wanted to 'submit' all the data as soon as the user either clicks on submit or presses the enter/return key.
I've been testing a bit with KeyEvents but nothing so far worked.
void tbPassword_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
}
The above code was to test if the event even worked in the first place.
It works perfectly, when I press 'd' it shows me 'd' when I press '8' it shows me '8' but pressing enter doesn't do anything.
So I though this was because enter isn't really bound to a character but it did show backspace, it worked just fine so it got me confused about why it didn't register my enter key.
So the question is:
How do I log the enter/return key? and why doesn't it log the key press right right now like it should?
note: I've put the event in a textbox
tbPassword.KeyPress += new KeyPressEventHandler(tbPassword_KeyPress);
So it fires when the enter button is pressed WHILE the textbox is selected (which is was the whole time of course) maybe that has something to do with the execution of the code.
Do you have a button defined as the default action?
If so then that control will gobble up the Enter key.
And maybe that is your answer. You need to set the DefaultAction property to true on your submit button.
Try the KeyDown event instead.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter");
}
}
Perhaps you should use the "AcceptButton" of the form to set it to the submit button. Think that is what you what really...
You have left out a vital bit, you must set the Handled property to true or false depending on the condition...
void tbPassword_KeyPress(object sender, KeyPressEventArgs e)
{
MessageBox.Show(e.KeyChar.ToString());
if (e.KeyCode == Keys.Enter){
// This is handled and will be removed from Windows message pump
e.Handled = true;
}
}
Try this
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
MessageBox.Show("Enter Key Pressed", "Enter Key Pressed", MessageBoxButtons.OK);
}
}
go to your forms...
in the basic form change this
FormName.AcceptButton = buttonName;
this would read the key log file of enter... automatically..
you can do this if you dont want users to see accept button
buttonName.Visible = false;
FormName.AcceptButton = buttonName;
AcceptButton automatically reads the enter key from the keyboard

Categories

Resources