Imports System.Math Private Sub txtAADT_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAADT.KeyPress # If the keystroke is not a numeric digit, the keystroke will be disregarded. Code works for any Textbox KeyPress event. If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True End If End Sub Private Sub txtAADT_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtAADT.Leave # User has completed their entry and is leaving the Textbox. # Create a Textbox variable to make the code below generic so that it can be pasted into any Textbox Leave event Dim tbx As System.Windows.Forms.TextBox = sender Dim value As Double If Not Double.TryParse(tbx.Text, value) Then # The user did not correct an invalid entry so replace it with 1 tbx.Text = 1 ElseIf value < -1 Then # The user pasted a negative value, so make sure it is rounded and take its absolute value tbx.Text = Abs(CLng(value)) ElseIf value < 1 Then # The user has entered 0 or pasted in a value between -1 and 1, so replace with minimum value of 1 tbx.Text = 1 ElseIf value = vbNull Then # The user has blanked out the Textbox, so fill in the Textbox with the minimum value of 1 tbx.Text = 1 Else # The user has entered a valid postive number, so make sure it is rounded and appears as a conventional number tbx.Text = CLng(value) End If End Sub
Imports System.Math Private Sub txtDistance1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtDistance1.KeyPress # Create a Textbox variable so that the code within this KeyPress event is generic for all positive Double Textboxes. Dim tbx As System.Windows.Forms.TextBox = sender If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And tbx.Text.IndexOf(".") < 0) Or (e.KeyChar = "." And tbx.Text.IndexOf(".") >= 0 And tbx.SelectionLength > 0 And tbx.SelectionStart <= tbx.Text.IndexOf(".") And tbx.SelectionStart + tbx.SelectionLength > tbx.Text.IndexOf("."))) Then # Explanation: Prevent the keystroke if it is not a numeric digit, a non-printable character such as a Backspace, or a decimal point where no decimal point exists in the Textbox or where the existing decimal point is contained in a text selection that will be overwritten by the new decimal point. e.Handled = True End If End Sub Private Sub txtDistance1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDistance1.Leave # User has completed their entry and is leaving the Textbox # Create a Textbox variable so that the code below is generic and can be pasted into any Textbox Leave event Dim tbx As System.Windows.Forms.TextBox = sender Dim value As Double If Not Double.TryParse(tbx.Text, value) Then # Textbox value is invalid, so replace it with the minimum default value (in this case 0) tbx.Text = 0 ElseIf value = vbNull Then # The user has blanked out the Textbox, so fill in the Textbox with the minimum value of 0 tbx.Text = 0 ElseIf value >= 0 Then # value is positive so round to 4 decimal places and correct to conventional format tbx.Text = Round(value, 4) Else # value is negative so round to 4 decimal places, apply the absolute value and correct to conventional format tbx.Text = Abs(Round(value, 4)) End If End Sub
Is there a way to detect that a hot key was used?
You would assign the hot key by setting the Text property of your button, so you would be in control of that. An end user can not create their own hot key, that I am aware of.
I wasn't refering to whether or not a hot key had been set up. I was asking if I can detect that the hot key event was activated by the user as distinguished from the button press event?
# Create a Textbox variable to make the code below generic so that it can be pasted into any Textbox Leave event
private void submit(){ if(isReady()){ JOptionPane.showMessageDialog(this, "Form Submitted"); } } private boolean isReady(){ boolean ready1 = false; boolean ready2 = false; boolean ready3 = false; if(isDouble(textField.getText())){ ready1 = true; label.setText(""); } else { label.setText("invalid entry"); } if(isDouble(textField_1.getText())){ ready2 = true; label_1.setText(""); } else { label_1.setText("invalid entry"); } if(isDouble(textField_2.getText())){ ready3 = true; label_2.setText(""); } else { label_2.setText("invalid entry"); } return (ready1 && ready2 && ready3); } private boolean isDouble(String x){ try{ Double.valueOf(x); return true; } catch (NumberFormatException e){ return false; } }
I am posting this in case it helps others and also to see if anyone has a more elegant way of doing this.
Unless your users know in advance, how would they know your text box is expecting a integer vs a double?
Perhaps you need to deal with the fact that if you were posting this thread to see if anyone has a more elegant way of handling user input validation, it might be worthwhile to be polite to those who take the time to respond.
' These are the minimum reference imports required for this code. Imports System.Windows.Forms Imports System.Globalization Imports System.Text.RegularExpressions ' At this time the Code is within a Form class Private Sub txtToDate_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtToDate.TextChanged If TypeOf sender Is TextBox Then ' Just a failsafe to be sure that only a textbox is the sender object Dim tbx As TextBox = sender ' call the Date Character validation Sub TextBoxDateText(tbx) End If End Sub ' The code that follows could be moved out of the Form class into a helper class dll. Private Sub TextBoxDateText(ByVal tbx As TextBox) If Len(tbx.Text) > 0 Then ' Only testing for valid characters when at least 1 character has been entered into the Textbox. ' Variables for the cursor position in the textbox, the character length of the text, and the actual text value Dim tbxPos As Long = tbx.SelectionStart Dim tbxLen As Long = Len(tbx.Text) Dim tbxText As String = tbx.Text ' Get the user's local Date Separator character(s). Escapes need to be added in front of . or \ characters, ' but that is not needed in the U.S. Dim dateSep As String = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator ' Create a regular expression string of characters I want to allow. In this case it is the Date Separator character ' and any decimal digit (\d is a special group that matches decimal digits for the user's local culture. Dim validChars As String = dateSep & "\d" ' Test the text in the Textbox for any character that is not part of the validChar string. See Function below. If Not IsValidChars(tbxText, validChars) Then ' One or more invalid characters was found so get the text with only valid characters. See Function below. tbxText = KeepValidChars(tbxText, validChars) ' Set where the cursor would go and the new text character length after stripping out invalid characters tbxPos = tbxPos - (tbxLen - Len(tbxText)) tbxLen = Len(tbxText) End If ' Test if the maximum character count is exceed. Here it is hard coded, but in future posts ' I will change it to a parameter variable. If tbxLen > 10 Then ' The text is still longer than the maximum character count so remove excess characters to the left of the cursor ' This code assumes the Textbox flag is set for left to right entry. Change to the right of the cursor if you use the opposite. ' Explanation of Substring expression below: Start at beginning of string. From the cursor position going left remove ' any characters that would exceed the maximum allowed. Concatenate whatever remains with ' everything to the right of the cursor. tbxText = tbxText.Substring(0, tbxPos - (tbxLen - 10)) & tbxText.Substring(tbxPos, tbxLen - tbxPos) ' Set the new cursor position and the new text character length that applies after characters maximum is respected tbxPos = tbxPos - (tbxLen - 10) tbxLen = Len(tbxText) End If ' Test if any of the above operations would change the text of the Textbox. If tbx.Text <> tbxText Then ' Text changed so replace what is in the Textbox with the character validated text ' and set the new cursor position to be immediately to the right of the last retained inserted character. tbx.Text = tbxText tbx.SelectionStart = tbxPos End If ' end of operations on Textbox text with one or more characters entered. End If End Sub Private Shared Function IsValidChars(ByVal txtDate As String, ByVal validChars As String) As Boolean ' Declare a regular expression which is the negation in any position of the provided valid characters Dim objNotDatePattern As New Regex("[^" & validChars & "]+") ' A match occurs if invalid characters are present, but return the match's negation to ' report true when only valid characters are present. Return (Not objNotDatePattern.IsMatch(txtDate)) End Function Function KeepValidChars(ByVal input As String, ByVal validChars As String) As String ' Making a change that could trigger an error so place in try block. Try ' Replace any invalid character with no character, so that only valid characters in the validChars list will remain. Return Regex.Replace(input, _ "[^" & validChars & "]", _ "", RegexOptions.None) Catch e As Exception Return input End Try End Function