Control KeyDown Event Trap CTRL-C etc - vb.net

I'm having a problem with processing CTRL-C, CTRL-V, CTRL-X on my form.
Private Function HandleKeyDown(sender As Object,
e As KeyEventArgs,
ByVal vShow As String) As Boolean
HandleKeyDown = False
If e.KeyCode = Keys.F1 Then
Help.ShowPopup(Me, vShow, Cursor.Position)
End If
If e.KeyCode = Keys.C AndAlso e.Modifiers = Keys.Control Then
sender.Copy()
ElseIf e.KeyCode = Keys.V AndAlso e.Modifiers = Keys.Control Then
sender.Paste()
ElseIf e.KeyCode = Keys.X AndAlso e.Modifiers = Keys.Control Then
sender.Cut()
Else
Console.WriteLine(String.Format("Modifiers:{0} KeyCode:{1} KeyData:{2} KeyValue:{3} ", e.Modifiers.ToString, e.KeyCode.ToString, e.KeyData.ToString, e.KeyValue.ToString))
End If
HandleKeyDown = True
End Function
The KeyDown event never picks up the second key. The only value the KeyCode ever seems to hold is Keys.Control. This is what the Console.WriteLine outputs for CTRL-C
Modifiers:Control KeyCode:ControlKey KeyData:ControlKey, Control KeyValue:17
Where am I going wrong?

Are you calling this from the actual event handler? I had to add "Handles MyBase.KeyDown" and remove your extra parameter.
Private Sub HandleKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles MyBase.KeyDown
'HandleKeyDown = False
If e.KeyCode = Keys.C AndAlso e.Modifiers = Keys.Control Then
MessageBox.Show(String.Format("Modifiers:{0} --- KeyCode:{1} --- KeyData:{2} --- KeyValue:{3} ",
e.Modifiers.ToString, e.KeyCode.ToString, e.KeyData.ToString, e.KeyValue.ToString))
'sender.Copy()
ElseIf e.KeyCode = Keys.V AndAlso e.Modifiers = Keys.Control Then
MessageBox.Show(String.Format("Modifiers:{0} --- KeyCode:{1} --- KeyData:{2} --- KeyValue:{3} ",
e.Modifiers.ToString, e.KeyCode.ToString, e.KeyData.ToString, e.KeyValue.ToString))
'sender.Paste()
ElseIf e.KeyCode = Keys.X AndAlso e.Modifiers = Keys.Control Then
MessageBox.Show(String.Format("Modifiers:{0} --- KeyCode:{1} --- KeyData:{2} --- KeyValue:{3} ",
e.Modifiers.ToString, e.KeyCode.ToString, e.KeyData.ToString, e.KeyValue.ToString))
'sender.Cut()
End If
'HandleKeyDown = True
End Sub
It's working for me. I get a value of 88, 67, and 86 respectively.

Related

Formatting a number with commas and cents while typing in textbox

Pro devs, I want to ask questions on you. I expect you could help me. My question is: I have a Textbox named "txtUnitPrice" what I need is when I type a number on it it will auto-generate the commas and decimals of that number, example: when I type a number "4" it will display "4.00" and when I type "1000" it will display "1,000.00" how can I do that, please help me.
I tried many questions here that are related to my problem but none of them can help me.
Here's my code:
Private Sub txtUnitPrice_TextChanged(sender As Object, e As EventArgs) Handles txtUnitPrice.TextChanged
Dim input As Double = Double.Parse(txtUnitPrice.Text)
Dim inputNumWithCommas As String = input.ToString("N0", CultureInfo.InvariantCulture)
txtUnitPrice.Text = inputNumWithCommas
End Sub
The code above is not my desired output. Please help me thanks.
For now a easy way would be to add a button under the textbox and then use this for when the button is pressed and after you input a number to txtUnitPrice
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
txtUnitPrice.Text = FormatCurrency(txtUnitPrice.Text)
End Sub
Another way which will update in real time without the need of a button would be something similar to this
Dim strCurrency As String = ""
Dim acceptableKey As Boolean = False
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtUnitPrice.KeyDown
If (e.KeyCode >= Keys.D0 And e.KeyCode <= Keys.D9) OrElse (e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9) OrElse e.KeyCode = Keys.Back Then
acceptableKey = True
Else
acceptableKey = False
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtUnitPrice.KeyPress
' Check for the flag being set in the KeyDown event.
If acceptableKey = False Then
' Stop the character from being entered into the control since it is non-numerical.
e.Handled = True
Return
Else
If e.KeyChar = Convert.ToChar(Keys.Back) Then
If strCurrency.Length > 0 Then
strCurrency = strCurrency.Substring(0, strCurrency.Length - 1)
End If
Else
strCurrency = strCurrency & e.KeyChar
End If
If strCurrency.Length = 0 Then
txtUnitPrice.Text = ""
ElseIf strCurrency.Length = 1 Then
txtUnitPrice.Text = "0.0" & strCurrency
ElseIf strCurrency.Length = 2 Then
txtUnitPrice.Text = "0." & strCurrency
ElseIf strCurrency.Length > 2 Then
txtUnitPrice.Text = strCurrency.Substring(0, strCurrency.Length - 2) & "." & strCurrency.Substring(strCurrency.Length - 2)
End If
txtUnitPrice.Select(TextBox1.Text.Length, 0)
End If
e.Handled = True
End Sub
May want to change a few things but ill leave that up to you to play with.

Convert Sub to Class for multiple CurrTextBox's

I have been using the following Subs to check and ensure data entered into a TextBox is numeric and it then gets converted to currency decimals in a form with a single CurrTextBox, however I have now been tasked to create a form with multiple CurrTextBox's.
How would I convert the following code to handle multiple calls. I suppose I can create a Public Sub that the data entered into a particular CurrTextBox calls... Ideas?
Private Sub CurrBox2_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
If (e.KeyCode >= Keys.D0 And e.KeyCode <= Keys.D9) OrElse (e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9) OrElse e.KeyCode = Keys.Back Then
acceptableKey = True
Else
acceptableKey = False
End If
End Sub
' This sub handles the keypress inputs and ensures values are numeric only
Private Sub CurrBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
' Check for the flag being set in the KeyDown event.
If acceptableKey = False Then
' Stop the character from being entered into the control since it is non-numerical.
e.Handled = True
Return
Else
If e.KeyChar = Convert.ToChar(Keys.Back) Then
If strCurrency.Length > 0 Then
strCurrency = strCurrency.Substring(0, strCurrency.Length - 1)
End If
Else
strCurrency = strCurrency & e.KeyChar
End If
If strCurrency.Length = 0 Then
CurrBox2.Text = ""
ElseIf strCurrency.Length = 1 Then
CurrBox2.Text = "0.0" & strCurrency
ElseIf strCurrency.Length = 2 Then
CurrBox2.Text = "0." & strCurrency
ElseIf strCurrency.Length > 2 Then
CurrBox2.Text = strCurrency.Substring(0, strCurrency.Length - 2) & "." & strCurrency.Substring(strCurrency.Length - 2)
End If
CurrBox2.Select(CurrBox2.Text.Length, 0)
End If
e.Handled = True
End Sub
One event can handle multiple controls.
Just add more controls after Handles clause in your events and all of these to be handled.
Private Sub CurrBox2_KeyDown(ByVal sender As Object, ByVal e System.Windows.Forms.KeyEventArgs) Handles currbox1.keydown, currbox2.keydown, currbox3.keydown
If (e.KeyCode >= Keys.D0 And e.KeyCode <= Keys.D9) OrElse (e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9) OrElse e.KeyCode = Keys.Back Then
acceptableKey = True
Else
acceptableKey = False
End If
End Sub
This way you need write those events only once.
I hope I was undertand your question right.

SendKeys not working in Datagridview keydown event

I have a Datagridview on my form with two columns. I only want the cells in the first column to be selected. So I'm using the datagridview's keydown event to capture the TAB and SHIFT+TAB. So if the first row is selected and the user presses tab, the second row will be selected instead of staying on the first row and selecting the second column's cell.
My if statement for the TAB key is working fine, but for some reason the SHIFT+TAB statement isn't. The cell above the currently selected cell isn't getting selected. Nothing happens.
Private Sub myGrid_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles myGrid.KeyDown
If e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
SendKeys.Send("{DOWN}")
End If
If e.Modifiers = Keys.Shift AndAlso e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
SendKeys.Send("{UP}")
End If
End Sub
The really weird thing though is if I add a messagebox into the statement it works.
If e.Modifiers = Keys.Shift AndAlso e.KeyCode = Keys.Tab Then
MsgBox("test")
e.SuppressKeyPress = True
SendKeys.Send("{UP}")
End If
Any ideas?
Sendkeys is a last, last resort...
How about something like this:
Private Sub dgv_KeyDown(sender As Object, e As KeyEventArgs) Handles dgv.KeyDown
If e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
dgv.CurrentCell = dgv(0, dgv.CurrentCell.RowIndex + 1)
End If
End Sub
With the help from #rheitzman I was able to see the main issue. The issue came from having the TAB and SHIFT+TAB in two different if statements. Here's my updated code:
Private Sub myGrid_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles myGrid.KeyDown
Dim row As String = Me.myGrid.CurrentCellAddress.Y
If e.Modifiers = Keys.Shift AndAlso e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
Me.myGrid.CurrentCell = Me.myGrid.Rows(row - 1).Cells(0)
Me.myGrid.Rows(row - 1).Cells(0).Selected = True
ElseIf e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
Me.myGrid.CurrentCell = Me.myGrid.Rows(row + 1).Cells(0)
Me.myGrid.Rows(row + 1).Cells(0).Selected = True
End If
End Sub
Tab and Shift+Tab are already handled by Windows Forms and DataGridView. They move the cell highlighter/selector move left(previous) and right(next). You'd have to create a class that inherits DataGridView and manually override their functionality to achieve what you want, then use that new class for your data grid.
Private Sub DataGridView1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
Dim r As Integer = Me.DataGridView1.CurrentCellAddress.Y
Dim f As Integer = Me.DataGridView1.CurrentCellAddress.X
If e.Modifiers = Keys.Shift AndAlso e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
If 0 = r Then
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(f - 1)
Me.DataGridView1.Rows(DataGridView1.RowCount - 1).Cells(f - 1).Selected = True
Else
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(r - 1).Cells(f)
Me.DataGridView1.Rows(r - 1).Cells(f).Selected = True
End If
ElseIf e.KeyCode = Keys.Tab Then
e.SuppressKeyPress = True
If DataGridView1.RowCount = (r + 1) Then
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(0).Cells(f + 1)
Me.DataGridView1.Rows(0).Cells(f + 1).Selected = True
Else
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(r + 1).Cells(f)
Me.DataGridView1.Rows(r + 1).Cells(f).Selected = True
End If
End If
End Sub

Detect Print Screen keyup and keydown in Keyboard Tester app VB NET

I have a problem when I try to make Keyboard Tester application for my small office.
I cant detect print screen keycode e.keycode = keys.PrintScreen.
I will do something like change picturebox back color when a key down, but it seems doesnt work with print screen, nothing happen.
my code is:
Private Sub keyboardmenu_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
'Esc + Function Keys -----------------------------------------
If e.KeyCode = Keys.Escape Then
EscBox.BackColor = Color.Red
End If
If e.KeyCode = Keys.F1 Then
F1Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F2 Then
F2Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F3 Then
F3Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F4 Then
F4Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F5 Then
F5Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F6 Then
F6Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F7 Then
F7Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F8 Then
F8Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F9 Then
F9Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F10 Then
F10Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F11 Then
F11Box.BackColor = Color.Red
End If
If e.KeyCode = Keys.F12 Then
F12Box.BackColor = Color.Red
End If
'End of Esc + Function Keys -----------------------------------------
Private Sub keyboardmenu_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
'Esc + Function Keys ----------------------------------------
If e.KeyCode = Keys.F1 Then
F1Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F2 Then
F2Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F3 Then
F3Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F4 Then
F4Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F5 Then
F5Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F6 Then
F6Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F7 Then
F7Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F8 Then
F8Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F9 Then
F9Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F10 Then
F10Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F11 Then
F11Box.BackColor = Color.Transparent
End If
If e.KeyCode = Keys.F12 Then
F12Box.BackColor = Color.Transparent
End If
'End of Esc + Function Keys -----------------------------------------
End Sub
Please help me. Idk if there are more keys like print screen problem.
Thank You
I'm not sure of the real reason, but I've read about it before and came to the conclusion that Windows is protecting that key's event from being easily handled. Someone else probably knows better, but this works:
Protected Overrides Function ProcessKeyEventArgs(ByRef msg As Message) As Boolean
If msg.WParam = Keys.PrintScreen Then
MessageBox.Show("PrintScreen key press detected!")
End If
Return MyBase.ProcessKeyEventArgs(msg)
End Function
Also, you should put all of those if statements in a Select Case statement:
Private Sub keyboardmenu_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.Escape
EscBox.BackColor = Color.Red
Case Keys.F1
F1Box.BackColor = Color.Red
Case Keys.F2
F2Box.BackColor = Color.Red
'Etc
End Select
End Sub
This comment is on the IF statements and CASE suggestion, otherwise I concur with the answer by Keith.
I use this sort of thing fairly often, but it's crazy to put all those IF statements, OR the Case statement:
Simply name the boxes to match the enumeration, then (assuming Controls is the parent container of all the boxes)
Controls(e.keycode.tostring & "box").backcolor = Color.Red
and
Controls(e.keycode.tostring & "box").backcolor = Color.Transparent
This one line will replace everything (if you rename the escbox to escapebox)
Of course, you might want to do some checking like
If Controls.ContainsKey(e.keycode.tostring & "box") Then ...

How to only allow digits and dots in a textbox?

I'm wondering how I can get my textbox to only accept digits and dots, like:
123.45
or 115
or 218.16978
etc.
I already have the following code:
Private Sub TxtHStof_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtHStof.KeyPress
e.Handled = Not Char.IsDigit(e.KeyChar)
End Sub
But that only allows digits without the dots.
How can I change the code so it does allows the dots as well, but nothing else?
e.Handled = Not (Char.IsDigit(e.KeyChar) OR e.KeyChar=".")
The accepted solution doesn't cater for
Multiple entries of decimals for example "12....1234"
OS specific decimal separators
This works for me
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Dim DecimalSeparator As String = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator
e.Handled = Not (Char.IsDigit(e.KeyChar) Or
Asc(e.KeyChar) = 8 Or
(e.KeyChar = DecimalSeparator And sender.Text.IndexOf(DecimalSeparator) = -1))
End Sub
You should use a MaskedTextBox - see here on how to set the format string (which allows you to restrict to digits and decimal point only)
http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask.aspx
With this code you can use ',' (Europe) and '.' (American) decimals.
Private Sub TGewicht_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TGewicht.KeyPress
e.Handled = Not (Char.IsDigit(e.KeyChar) Or Asc(e.KeyChar) = 8 Or ((e.KeyChar = "." Or e.KeyChar = ",") And (sender.Text.IndexOf(".") = -1 And sender.Text.IndexOf(",") = -1)))
End Sub
'****To Allow only Numbers with Decimal and BACKSPACE enabled****
If Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".") And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
Coming from C# and not VB, I'm taking a stab at this, but would this work:
e.Handled = Not (Char.IsDigit(e.KeyChar) AndAlso e.KeyChar.Equals('.'))
Insert function in MODULE o FORM
Public Sub OnlyNumber(Ct As TextBox, MaxLength As Integer)
Ct.MaxLength = MaxLength
AddHandler Ct.KeyPress, AddressOf ValidarTeclaNumeros
End Sub
Private Sub ValidarTeclaNumeros(sender As Object, e As KeyPressEventArgs)
Dim Ct As TextBox
Ct = sender
If [Char].IsDigit(e.KeyChar) OrElse [Char].IsControl(e.KeyChar) Then
'ok
'e.Handled = True
ElseIf [Char].IsPunctuation(e.KeyChar) Then
If (Ct.Text.Contains(",") OrElse Ct.Text.Contains(".")) Then
e.Handled = True
End If
Else
e.Handled = True
End If
End Sub
In load form add this code for your control only numerical (and only one comma or doc)
OnlyNumber(txtControl, 10)
I started with mostly the same question, but I did care about being able to paste. While searching on the web for how to do this, I found that I really should handle:
Periods or commas as the decimal indicator, depending on how your OS is set up.
Only allowing keypresses that conform to the pattern, while still allowing cursor control characters like arrows and backspace.
Only allowing pastes into the TextBox that conform to the pattern. I chose to this in a manner that, when pasting, the code treats the pasted text as if the text was being keyed in, so pasting "a1b.c2d,e3f.g4h,i5j" into the TextBox would show up as "1.2345" if periods are your decimal indicator, and "12,345" if commas are your decimal indicator.
I tried the MaskedTextBox and really did not like it, as it enforced the decimal point location where I really just wanted to be able to freely fill in any numeric. I may have gone a little overboard using a RegEx for the pattern matching, but now I should be able to reuse this code pretty much anywhere.
Public Class frmMain
Dim RegexValidator As System.Text.RegularExpressions.Regex
Dim FormLoaded As Boolean = False
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim RegexDecimalPattern As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
RegexDecimalPattern = IIf(RegexDecimalPattern = ".", "\.", RegexDecimalPattern)
RegexValidator = New System.Text.RegularExpressions.Regex("^\d*" & RegexDecimalPattern & "?\d*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
FormLoaded = True
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
' Code below is based on
' http://www.vbforums.com/showthread.php?626378-how-to-validate-textbox-allows-only-numeric-and-decimal-in-vb-net
' but was modified to be based on Regex patterns.
'
' Note that:
' KeyPress event validation covers data entry as it is being typed.
' TextChanged event validation covers data entry by cut/pasting.
If Char.IsControl(e.KeyChar) Then
'Allow all control characters.
Else
Dim Text = Me.TextBox1.Text
Dim SelectionStart = Me.TextBox1.SelectionStart
Dim SelectionLength = Me.TextBox1.SelectionLength
Text = Text.Substring(0, SelectionStart) & e.KeyChar & Text.Substring(SelectionStart + SelectionLength)
If Not RegexValidator.IsMatch(Text) Then e.Handled = True
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
' If default text is used in a textbox, a TextChanged event occurs before
' RegexValidator is initialized during the Form Load, so we need to check.
If FormLoaded Then
' Note that:
' KeyPress event validation covers data entry as it is being typed.
' TextChanged event validation covers data entry by cut/pasting.
Dim Text = Me.TextBox1.Text
Dim ValidatedText As String = ""
Dim KeyChar As Char
For Each KeyChar In Text
If RegexValidator.IsMatch(ValidatedText + KeyChar) Then ValidatedText += KeyChar
Next
If (ValidatedText.Length > 0) And (TextBox1.Text <> ValidatedText) Then
Me.TextBox1.Text = ValidatedText
Me.TextBox1.SelectionStart += ValidatedText.Length
End If
End If
End Sub
End Class
im late for the party but here is my code
Private Sub LoanFeeTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles LoanFeeTextBox.KeyPress
If Char.IsControl(e.KeyChar) Then
ElseIf Char.IsDigit(e.KeyChar) OrElse e.KeyChar = "."c Then
If LoanFeeTextBox.TextLength = 12 And LoanFeeTextBox.Text.Contains(".") = False Then
LoanFeeTextBox.AppendText(".")
ElseIf e.KeyChar = "." And LoanFeeTextBox.Text.IndexOf(".") <> -1 Then
e.Handled = True
ElseIf Char.IsDigit(e.KeyChar) Then
If LoanFeeTextBox.Text.IndexOf(".") <> -1 Then
If LoanFeeTextBox.Text.Length >= LoanFeeTextBox.Text.IndexOf(".") + 3 Then
e.Handled = True
End If
End If
End If
Else
e.Handled = True
End If
End Sub
Private Sub TextBox2_KeyPress(
ByVal sender As Object,
ByVal e As System.Windows.Forms.KeyPressEventArgs
) Handles TextBox2.KeyPress
e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or Asc(e.KeyChar) = 8)
End Sub
Just adding another solution. This code restricts user to entering only one "." decimal point, only two places beyond the decimal point, can set how many digits you want to use (currently I have it set to only allow up to to 5 whole numbers before the decimal. Also allows use of backspace and delete. That way they can't fat finger an extra "." and end up with something like "45.5.5".
If Char.IsControl(e.KeyChar) Then
ElseIf Char.IsDigit(e.keyChar) OrElse e.keyChar = "."c Then
If Amount_FundedTextBox.TextLength = 5 And Amount_FundedTextBox.Text.Contains(".") = False Then
Amount_FundedTextBox.AppendText(".")
ElseIf e.KeyChar = "." And Amount_FundedTextBox.Text.IndexOf(".") <> -1 Then
e.Handled = True
ElseIf Char.IsDigit(e.KeyChar) Then
If Amount_FundedTextBox.Text.IndexOf(".") <> -1 Then
If Amount_FundedTextBox.Text.Length >= Amount_FundedTextBox.Text.IndexOf(".") + 3 Then
e.Handled = True
End If
End If
End If
Else
e.Handled = True
End If
You can restrict character entries in your textboxes by adding a "KeyPress" handler (from TextBox properties) and specifying allowable characters. If the character is "handled" then it is not permitted.
Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox.KeyPress
Dim txt As TextBox = CType(sender, TextBox)
If Not ((Char.IsDigit(e.KeyChar)) Or (e.KeyChar = "E") Or (e.KeyChar = "e") Or (e.KeyChar = "-")) Then e.Handled = True
If e.KeyChar = Chr(8) Then e.Handled = False 'allow Backspace
If e.KeyChar = "." And txt.Text.IndexOf(".") = -1 Then e.Handled = False 'allow single decimal point
If e.KeyChar = Chr(13) Then GetNextControl(txt, True).Focus() 'Enter key moves to next control
End Sub
Private Sub TextBox4_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox4.KeyPress
' its worked for only number with point and worked backspace
If Not Char.IsDigit(e.KeyChar) And Not e.KeyChar = "." Then
e.Handled = True
End If
If e.KeyChar = "." And TextBox4.Text.IndexOf(".") <> -1 Then
e.Handled = True
End If
If e.KeyChar = "." Then
e.Handled = False
End If
If e.KeyChar = Chr(Keys.Back) Then
e.Handled = False
End If
If Char.IsDigit(e.KeyChar) Then
If TextBox4.Text.IndexOf(".") <> -1 Then
If TextBox4.Text.Length >= TextBox4.Text.IndexOf(".") + 3 Then 'replace 2 for greater numbers after decimal point
e.Handled = True
TextBox4.Focus()
End If
End If
End If
' is for only digit with back space
e.Handled = Not Char.IsDigit(e.KeyChar)
If e.KeyChar = Chr(Keys.Back) Then
e.Handled = False
End If
If Char.IsDigit(e.KeyChar) Then
If TextBox4.Text.IndexOf(".") <> -1 Then
If TextBox4.Text.Length >= TextBox4.Text.IndexOf(".") + 3 Then 'replace 2 for greater numbers after decimal point
e.Handled = True
TextBox4.Focus()
End If
End If
End If
End Sub
Dim e As System.Windows.Forms.KeyPressEventArgs
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
Else
e.Handled = False
End If