My form has one textbox for input, listview for save.
User input number in textbox, and input enter, program check input number length and duplication
textbox KeyUp Event
private void txb_MList_num_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (check_MList_dup())
{
lstv_MList.Items.Add(txb_MList_num.Text);
allList.Add(txb_MList_num.Text);
txb_MList_num.Text = "";
}
}
}
check_MList_dup()
private bool check_MList_dup()
{
bool OK = true;
if (txb_MList_num.TextLength < 11)
{
MessageBox.Show("Input more text(length = 11)");
return false;
}
else
{
for (int i = 0; i < allList.Count; i++)
if (allList[i].Equals(txb_MList_num.Text))
{
MessageBox.Show("It's duplication.");
return false;
}
}
return OK;
}
But User input enter for close MessageBox, program show MessageBox again, again...before using mouse.
I debug it use breakpoint, event is not occuer when MessageBox is showing.
But delete breakpoint, MessageBox is repeated.
I use e.KeyCode == Keys.Enter && this.Focused
but this.Focused always return false .
How can I close MessageBox?
You can try and use txb_MList_num.KeyDown event
As per MSDN:-
"KeyDown event Occurs when a key is pressed while the control has focus."
You can use PreviewKeyDown:
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.Enter))
{
// Do your staff here...
}
}
Related
I am trying to warn the user when they select and delete text in a wpf textbox.
I am able to trap the delete event using the previewkeydown event, but its is canceling out the delete event. Even when you press ok in the code below - deletion does not happen. I am missing something ...
private void TextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Delete)
{
var textbox = (TextBox)sender;
if (textbox.SelectionLength > 1)
{
var result = MessageBox.Show("Delete selected?", "MyApp", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.Cancel)
{
e.Handled = true;
}
}
}
}
This does not seem to be the proper usage of the PreviewKeyDown event handler. That handler seems to be meant to redirect non-standard input key events to do custom behavior. The delete key is not considered non-standard/special.
You've got the right idea with your current code otherwise, but now you just need to actually delete the text in the textbox.
private void TextBox_KeyDownHandler(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Keys.Delete:
if (sender is TextBox tb)
{
if(tb.SelectionLength > 1 && MessageBox.Show("Delete?", "MyApp", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
tb.SelectedText = "";
}
}
e.Handled = true;
break;
}
}
Lastly, make sure you're actually subscribing your handlers
public MainWindow()
{
InitializeComponent();
MyTextBox.KeyDown += new KeyEventHandler(TextBox_KeyDownHandler);
}
StackOverflow may not be the correct place to as a why question, but I am looking for a because answer rather than a how to answer. I have already worked around the problem by disabling the handler in the hander.
The application has a DataGridView that displays inventory information during incoming inspection. The data grid is too wide for the screen and requires horizontal scrolling. To make the data easier to see and edit a modal editor has been added. There are 2 buttons to close the modal editor, either Save or Cancel. Using the close button at the top right corner of the modal editor form should perform the same action as the cancel button.
When the cancel button is clicked everything works fine. When the close button is clicked the modal editor FormClosed event fire twice. Why is the modal editor FormClosed event firing twice? Do I have a bug in my code?
private bool CancelModalEditor()
{
bool cancelled = false;
string cancelMsg = (_cancelClicked) ? "Canceling" : "Closing";
cancelMsg += " the editor will delete the Record with Serial Number: " + SerialNumber + " from the Audit Session. Is this what you want to do?";
DialogResult dlg = MessageBox.Show(cancelMsg, "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dlg == DialogResult.Yes)
{
SaveClicked = false;
}
else
{
cancelled = true;
}
return cancelled;
}
private void AEMEBtn_Cancel_Click(object sender, EventArgs e)
{
_cancelClicked = true;
if (!CancelModalEditor())
{
Close();
}
else
{
_cancelClicked = false;
}
}
private void AEModalEditor_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!_cancelClicked && !SaveClicked)
{
if (CancelModalEditor())
{
e.Cancel = true;
}
else
{
_cancelClicked = true; // Prevent Infite Loop
Close();
}
}
}
File where modal editor is invoked.
private void ModalEditorForm_Closed(object sender, FormClosedEventArgs e)
{
AEModalEditor modalEditor = (AEModalEditor)sender;
int currentRow = modalEditor.RowID - 1;
if (modalEditor.SaveClicked)
{
UpdateDataGridRowWithModalEditorValues(dgAssetDetails, currentRow, modalEditor.AssetControlsValues);
updateAuditDetailsDataGridRow(currentRow, modalEditor.AuditControlsValues);
UpdateAuditTextFields(modalEditor);
SelectAllCellsInRow(currentRow);
}
else
{
DeleteRowFromAllDataGridViews(modalEditor.SerialNumber, currentRow);
_previouslySelectedRow = -1;
}
// Save all records in either case so that session data isn't lost.
save(false);
_currentlySelectedDataGrid = DataGrids.None;
_modalEditorOpen = false;
txtSerialNumber.Focus();
}
Don't call close in the closing-event again. The form is already closing and don't need to be closed a second time.
private void AEModalEditor_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!_cancelClicked && !SaveClicked)
{
if (CancelModalEditor())
{
e.Cancel = true;
}
else
{
_cancelClicked = true;
// You called Close here again
Close();
}
}
}
Hello I just started in Xamarin with an Android project and I encountered a problem on the keypress of an edittext. When the Enter is fired on my first Edittext and it gives focus to the Edittext (txtArtikel), but then the keypress of this Edittext is triggered and jumps to the third Edittext. So it skips my second Edittext with just one Enter press. Can anyone help me?
txtArtikel.KeyPress += txtArtikelPress;
private void txtArtikelPress(object sender, View.KeyEventArgs e)
{
e.Handled = false;
if (e.KeyCode == Keycode.Enter)
{
txtAantal.RequestFocus();
}
}
EDIT
I'm still working with the Keypress and now looking for an Enter and Escape. When the txtWerf is empty it jumps to txtArtikel, but when it contains text it goes to txtAantal.
private void txtWerfPress(object sender, View.KeyEventArgs e)
{
if (e.KeyCode == Keycode.Enter && e.Event.Action == KeyEventActions.Down)
{
if (txtWerf.Text.Trim() != "")
{
if (txtArtikel.RequestFocus())
e.Handled = true;
}
}
else
e.Handled = false;
}
private void txtArtikelPress(object sender, View.KeyEventArgs e)
{
if (e.KeyCode == Keycode.Enter && e.Event.Action == KeyEventActions.Down)
{
if (txtArtikel.Text.Trim() != "")
{
if (txtAantal.RequestFocus())
e.Handled = true;
}
}
else if (e.KeyCode == Keycode.Escape && e.Event.Action == KeyEventActions.Down)
{
if (txtWerf.RequestFocus())
e.Handled = true;
}
else
Scanner.CheckForScannedData(sender, ref e);
e.Handled = false;
}
private void txtAantalPress(object sender, View.KeyEventArgs e)
{
if (e.KeyCode == Keycode.Escape && e.Event.Action == KeyEventActions.Down)
{
if (txtArtikel.RequestFocus())
e.Handled = true;
}
else
e.Handled = false;
}
You don't need to handle the KeyPress event in order to set the focus to the next EditText.
Android has a good algorithm that handles the focus when editing is done.
How does the app behave on pressing enter when you remove the event handler? Does it set the focus to the correct EditText? If it focuses he wrong view then you should take a look on how to
Move to another EditText when Soft Keyboard Next is clicked on Android.
If the focus doesn't change at all then you should tell Android what to do when the user has completed his input by using android:imeOptions: http://developer.android.com/guide/topics/ui/controls/text.html#Actions.
I'm new to C#. Using the code below, whenever I press a number key on my keyboard, it will display twice in the textbox. When I press "1" on the keyboard it will display
"11", and when I press "2" it will display "22". Why is this?
private void Window_TextInput(object sender, TextCompositionEventArgs e)
{
if(!isNumeric(e.Text))
{
string display = string.Empty;
display += e.Text;
displayNum(display);
}
else
{
String inputOperator = string.Empty;
inputOperator += e.Text;
if (inputOperator.Equals("+"))
{
ApplySign(sign.addition, "+");
}
}
}
private bool isNumeric(string str)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[^0-9]");
return reg.IsMatch(str);
}
private void window_keyUp(object sender, KeyEventArgs e)
{
if (e.Key >= Key.D0 && e.Key <= Key.D9)
{
int num = e.Key - Key.D0;
outputText2.Text += num;
}
}
private void BtnNum_Click(object sender, RoutedEventArgs e)
{
Button num = ((Button)sender);
displayNum(num.Content.ToString());
}
private void displayNum(String n)
{
if (operator1 == 0 && double.Parse(n) == 0)
{
}
else
{
if (operator1 == 0)
{
outputText2.Clear();
}
outputText2.Text += n;
operator1 = double.Parse(outputText2.Text);
outputText2.Text = Convert.ToString(operator1);
}
}
You have two events that are handeling the Keyboard events. Although not really sure what the displayNum() method is doing
I am assuming the Window_TextInput event is the event you wish to primarily handle the event.
Try adding
e.Handled = true;
In the Window_TextInput method. If that doesn't solve the problem can you post the displayNum() method?
EDIT:
After further review of the code and trying the same I do not see the relevance for the window_keyUp method as your Window_TextInput handles the input characters and has more applicable logic for handling the TextInput changes.
After I removed the window_keyUp event method the output appeared as expected (although commented out the ApplySign() method.
You've subscribed to two window-level text-related events - TextInput and KeyUp - and both of them end up appending input to the TextBox.
window_keyUp appends numbers to the TextBox
It looks like Window_TextInput is supposed to append non-numeric characters, but your RegEx is incorrect ([^0-9] matches anything that is not numeric, so IsNumeric returns True if the input is not a number)
The effect is that every numeric key press shows up twice.
I have a few controls in a Form, so I read and create a Event in the form that allows me to press ENTER to change the focus to another control. Here's the code:
private void frSeleccionEL_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Control nextControl = this.GetNextControl(ActiveControl, !e.Shift);
if (nextControl != null)
{
e.Handled = true;
if (!(nextControl is Label))
{
nextControl.Focus();
}
else //the next control is currently a label
{
nextControl = this.GetNextControl(ActiveControl, true);
while (nextControl != null)
{
nextControl.Focus();
if (!(nextControl is Label))
{
break;
}
nextControl = this.GetNextControl(ActiveControl, true);
}
}
}
}
}
In the textbox where it's not working, I have code for only numbers. Here's the code:
private void txtLocal_KeyPress(object sender, KeyPressEventArgs e)
{
//Para obligar a que sólo se introduzcan números
if (Char.IsDigit(e.KeyChar))
{
e.Handled = false;
}
else
{
if (Char.IsControl(e.KeyChar)) //permitir teclas de control como retroceso
{
e.Handled = false;
}
else
{
//el resto de teclas pulsadas se desactivan
e.Handled = true;
}
}
}
My problem is when I press ENTER in this control nothing happens, like ENTER was never pressed, because the event keypress for this control doesn't fire.
I deleted the control and remade it and the problem remains.
I don't know what is wrong.
Your first code is too long and we don't need it. If you want to turn Enter keypress into a Tab switch, using SelectNextControl method of your form. I can see your txtLocal_KeyPress does nothing with switching tab, so how you knew what happened or not. e.Handled only helps suppress the key press event or not. I guess your TextBox has Multiline = true; and you want to suppress the Enter keypress, instead switch to the next control, otherwise you don't have to suppress the Enter keypress in TextBox with Multiline=false. This short code will help you:
private void txtLocal_KeyPress(object sender, KeyPressEventArgs e){
if(e.KeyChar == 13)//Enter{
e.Handled = true;
SelectNextControl(txtLocal, true, true, true, true);
}
}
That's all to solve your problem.
I'm not sure if you know how to register a KeyPress event handler with your TextBox.KeyPress event, so I add this here to help you in that case:
txtLocal.KeyPress += txtLocal_KeyPress;
Try this:
private void txtLocal_KeyPress(object sender, KeyPressEventArgs e)
{
//Para obligar a que sólo se introduzcan números
if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar) )
{
e.Handled = true;
}
}
please use this code on form key down this will give you better performance
private void frSeleccionEL_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
ProcessTabKey(true);
}
}
please make sure you have set tab index on all of your control.
and then unchanged your text changed event code. it will be better if you use a custom text box instead of writing this code on all of your form.
Try this ......
private void txtLocal_KeyPress(object sender, KeyPressEventArgs e)
{
//Para obligar a que sólo se introduzcan números
if (Char.IsDigit(e.KeyChar) || asc(e.KeyChar)==13)
{
e.Handled = false;
}
else
{
if (Char.IsControl(e.KeyChar)) //permitir teclas de control como retroceso
{
e.Handled = false;
}
else
{
//el resto de teclas pulsadas se desactivan
e.Handled = true;
}
}
}
If you want to commit your changes with the enter key, assuming you want to update your data bindings, but stay in the control you can use the following code
private void TextBox_KeyPress(object sender, EventArgs e)
{
if(e.KeyCode == (char)Keys.Enter)
{
TextBox.DataBindings[0].WriteValue();
dataBindingSource.ResetCurrentItem();
TextBox.Select(TextBox.Text.Length, 0);
e.Handled = true;
}
}
The important part there is WriteValue() which commits the changes before the databind event fires. If you want other controls to update on your form after committing the changes, the ResetCurrentItem() will do this. Also, this code just commits the first binding value, but if you have multiple bindings you can step through them with a foreach loop and WriteValue() all of them or whatever. The TextBox.Select() line just keeps your cursor where you left it after pressing enter.