VB.net move between textboxes by keyboard arrow - vb.net

I Have VB.net application form with 10 horizontal text boxes . I need to move between text boxes with right And Left Keyboard Arrow . Also I need Make textBoxes Format To Be Like This 0.00

In addition to webdad3's answer.
Private Sub Form1_KeyDown(ByVal sender as Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
Dim tb as TextBox = TryCast(me.ActiveControl, TextBox)
If tb IsNot Nothing Then
Select Vase e.KeyCode
Vase Keys.Right, Keys.Left
dim forward as boolean = e.KeyCode = Keys.Right
me.SelectNextControl(Me, forward, True, True, true)
e.Handled = true
End Select
End If
End Sub
Don't forget to set Form.KeyPreview to true (via Forms Designer)
For the second part:
There are many, many different ways to format the text of a textbox.
The best solution would be to use DataBindings (complex topic, read a book about it.)
Public Class Form1
Public Property Price as Decimal
' call this code once
Private Sub InitControls()
Price = 3.45
me.txtPrice.DataBindings.Add(
"Text", Me, "Price", True,
DataSourceUpdateMode.OnPropertyChanged, Nothing, "0.00"
)
End Sub
End Class

I got the following code from the following link:
http://social.msdn.microsoft.com/Forums/windows/en-US/ffeeea42-f6ba-420f-827e-74879fd29b26/how-to-
detect-arrow-keys-in-vbnet?forum=winforms
Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
' Sets Handled to true to prevent other controls from
' receiving the key if an arrow key was pressed
Dim bHandled As Boolean = False
Select Case e.KeyCode
Case Keys.Right
'do stuff
e.Handled = True
Case Keys.Left
'do other stuff
e.Handled = True
Case Keys.Up
'do more stuff
e.Handled = True
Case Keys.Down
'do more stuff
e.Handled = True
End Select
End Sub

Related

Is there anyway to change ComboBox key inputs in VB.NET?

I have a combobox in my Userform. Whilst this is in focus, I am wanting to use the keyboard for WASD controls. However, I find that when I press WASD the Combobox is bringing up values beginning with these letters. Also, the arrow keys are cycling through the options as well.
Is there anyway to restrict these commands?
I have tried
Tool.AutoCompleteMode = AutoCompleteMode.None
This does not stop is doing this. Does anybody have any clue how I could access more specific controls to stop this kind of autofill happening?
If you have only the Combobox control in your form and no other input controls, such as textbox, you can try the following code:
Please set e.Handled = True in the KeyPress event of the Combobox.
Private Sub ComboBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ComboBox1.KeyPress
e.Handled = True
End Sub
If you have some input controls, you want to retain the editing function, and you want to not interfere with the KeyPress event of the form.
You could refer to the following steps.
(1) Please set Me.KeyPreview = False in the KeyDown event of each input control.
(2) Please set e.Handled = True in the KeyPress event of ComboBox1.
(3) When double-clicking the form to enter WASD, you can set ComboBox1.Focus().
Sample code:
Public Class Form1
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles MyBase.KeyPress
'edit your code
Dim offset As Integer = 10
If e.KeyChar = "a" Then
PictureBox1.Location = New Point(PictureBox1.Location.X - offset, PictureBox1.Location.Y)
ElseIf e.KeyChar = "w" Then
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - offset)
ElseIf e.KeyChar = "s" Then
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + offset)
ElseIf e.KeyChar = "d" Then
PictureBox1.Location = New Point(PictureBox1.Location.X + offset, PictureBox1.Location.Y)
End If
e.Handled = True
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.KeyPreview = True
End Sub
Private Sub Form1_DoubleClick(sender As Object, e As EventArgs) Handles MyBase.DoubleClick
ComboBox1.Focus()
Me.KeyPreview = True
End Sub
Private Sub ComboBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ComboBox1.KeyPress
e.Handled = True
End Sub
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
Me.KeyPreview = False
End Sub
End Class
Result:

Ignore enter keypress on dropdown with DropdownStyle=DropDownList

I've got a combobox, which the user can type into to filter out results.
To implement this, I've set the dropDownStyle to DropdownList and set the KeyUp event as follows
Private Sub cbRPP_KeyUp(ByVal sender As Object, ByVal e As KeyEventArgs) Handles cbRPP.KeyUp
If boredUserProtection Then Return
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
e.Handled = True
Return 'Boss doesn't want enter to do anything
End If
ComboKeyPressed()
End Sub
Private Sub cbRPP_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cbRPP.SelectionChangeCommitted
If boredUserProtection Then Return 'boredUserProtection = a flag to prevent the user from typing into the box once they've entered some text
Try
boredUserProtection = True
menuButton.Select()
TooltipNotify("Loading")
cbRPP.Text = String.Empty
LoadRegion()
menuButton.Select()
Catch ex As Exception
ErrorReporter.Program.ReportError(ex, "RPPCalibator", "Handled Gracefully")
Finally
boredUserProtection = False
End Try
End Sub
The problem is that my boss has now asked me to prevent any action from occuring when he presses the enter key.
I've attempted to achieve this by intercepting the keypress and suppressing if enter, but it seems that this doesn't work when dropdownStyle=dropdownList
Private Sub cbRPP_KeyPress(sender As Object, e As KeyPressEventArgs) Handles cbRPP.KeyPress
If e.KeyChar = vbCrLf Then
e.Handled = True
Return 'Boss doesn't want enter to do anything
End If
End Sub
Private Sub cbRPP_KeyDown(sender As Object, e As KeyEventArgs) Handles cbRPP.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
e.Handled = True
Return 'Boss doesn't want enter to do anything
End If
End Sub
I'm just wondering if anyone can shed any light on how I can prevent any events happening on enter keyprss, as the one piece of advice I can readily find on Google (intercepting KeyDown or KeyUp) don't seem to work.
(I'm a pragmatist, so whatever form of solution you have would be much appreciated)

textbox with numbers only but also pasting, copying, and selecting

I'm quite new in VB and got stuck on (i think) easy problem. I have a text box thats allows only numbers:
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 49 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
from 1 to 9. But this box doesnt allows me to paste, copy, and select text...how can i change it? I know that KeyCode for Control is 17, and for 'V' is 86, but have no idea how to use it...
thanks for any help
The issue with KeyPress is that it calls only one KeyPress at a time. Hence multiple selections such as Ctrl+V, Ctrl+C would not work. Instead of flagging it under KeyPress, call the TextChanged. Add the below mentioned and the issue should be resolved. Copy, Paste and Selecting would now work as normal.
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
TextBox2.Text = System.Text.RegularExpressions.Regex.Replace(TextBox2.Text, "[^\d]", "") 'Removes all character except numbers
TextBox2.Select(TextBox2.Text.Length + 1, 1) 'To bring the textbox focus to the right
End Sub
If you necessarily want a TextBox you could combine the KeyDown and KeyPress events in order to block anything that isn't numbers while manually allowing Copy, Paste, Cut, etc.
Imports System.Text.RegularExpressions
Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
e.Handled = Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False 'Verify if input is a number or a control character (such as Backspace).
End Sub
Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
e.SuppressKeyPress = True 'Start by blocking all key presses.
Select Case e.KeyData 'In order to not block some standard keyboard shortcuts.
Case Keys.Control Or Keys.C 'Copy
TargetTextBox.Copy()
Case Keys.Control Or Keys.X 'Cut
TargetTextBox.Cut()
Case Keys.Control Or Keys.V 'Paste
TargetTextBox.Paste()
TargetTextBox.Text = Regex.Replace(TextBox2.Text, "[^\d]", "")
Case Keys.Control Or Keys.A 'Select all.
TargetTextBox.SelectAll()
Case Else
e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
End Select
End Sub
EDIT: Pardon the unintentional similar Regex, Arun Kumar.
This worked for me , write the below code on textbox keypress event
Try
If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) AndAlso (e.KeyChar <> Chr(22)) Then
MsgBox("Please enter numeric values", MsgBoxStyle.Information)
e.Handled = True
End If
Catch ex As Exception
pObj.WriteErrorLog(Me.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ex, True)
End Try

Can't get KeyDown event on Tabpage

I have a TabControl with several TabPages, each containing a series of PictureBox. I want to be able to navigate with the arrow keys inside those TabPages. I tried to give .Focus() to the TabPage when the user selects it, and then trap the PreviewKeyDown and KeyDown events, but it does not work. I've put a breakpoint at the PreviewKeyDown event handler, and it is not event reached.
Here is the activation of the TabPage :
Sub TilesetsTab_Selected(ByVal sender As Object, ByVal e As TabControlEventArgs) Handles TilesetsTab.Selected
Dim myTab As TabControl = CType(sender, TabControl)
If myTab.TabCount = 0 Then Exit Sub
Active.Tileset = Project.Tileset(CInt(myTab.SelectedTab.Tag))
Active.Tileset.Tab.Focus()
End Sub
And here is the Key event handlers
Sub Tab_KeyPreviewDown(ByVal sender As Object, ByVal e As PreviewKeyDownEventArgs) Handles Tab.PreviewKeyDown
If e.KeyCode = Keys.Left Or e.KeyCode = Keys.Right Or e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Then e.IsInputKey = True
End Sub
Sub Tab_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles Tab.KeyDown 'BUG
Dim TilesWidth As Integer = Me.Tab.Width \ Me.ScreenSize
Select Case e.KeyCode
Case Keys.Left
If Active.Tile.Index = 0 Then Exit Sub
Me.Tile(Active.Tile.Index - 1).Selected()
Case Keys.Right
If Active.Tile.Index = Project.Tileset.Count - 1 Then Exit Sub
Me.Tile(Active.Tile.Index + 1).Selected()
Case Keys.Up
If Active.Tile.Index < TilesWidth Then Exit Sub
Me.Tile(Active.Tile.Index - TilesWidth).Selected()
Case Keys.Down
If Active.Tile.Index + TilesWidth > Active.Tileset.Count - 1 Then Exit Sub
Me.Tile(Active.Tile.Index + TilesWidth).Selected()
End Select
End Sub
Why can't I fire a KeyDown event on the TabPage ?
I don't know why the answer posted yesterday by someone (and the comments I made) were deleted, but it was said that TabPages could not have focus, and that it is restricted to TabControl. Following that advice, I shifted the PreviewKeyDown and KeyDown event handlers to TabControl events and it worked.
I'm losing some of the arrow navigation between TabPages, but it suits me.

How to avoid taking special characters in textbox of a Windows application

I am developing the Windows application.
I have a form and I am trying to validate the text box on that form.
I want to put some validation on a text box like the text box should accept only Alphabates, Didgits and comma.(No other characters like special symbols.)
As well, it should accept the Enter key when cursor is in that text box.
I am trying to write the code but some how its not working.
But its still taking special characters like <>/;'
What changes I have to made ?
here is the code...
Key Down Event
Private Sub txtOLDBuildingName_KeyDown(sender As Object, e As KeyEventArgs) Handles txtOLDBuildingName.KeyDown
' Initialize the flag to false.
nonNumberEntered = False
' Determine whether the keystroke is a number from the top of the keyboard.
If (e.KeyCode < Keys.D0 And e.KeyCode > Keys.D9) And (e.KeyCode > Keys.A And e.KeyCode < Keys.Z) Then
nonNumberEntered = True
End If
'If shift key was pressed, it's not a number.
If Control.ModifierKeys = Keys.Shift Then
nonNumberEntered = True
End If
End Sub
Key Press Event
Private Sub txtOLDBuildingName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtOLDBuildingName.KeyPress
If nonNumberEntered = True Then
e.Handled = True
End If
End Sub
Delete the sub which is handling KeyDown event and replace the sub which is handling KeyPress event to this one:
ReadOnly ValidChars As String = _
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,"
Private Sub txtOLDBuildingName_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) _
Handles txtOLDBuildingName.KeyPress
e.Handled = Not (ValidChars.IndexOf(e.KeyChar) > -1 _
OrElse e.KeyChar = Convert.ToChar(Keys.Back))
End Sub
Update:
This modification is more precise, it compares the clipbard content before paste them.
ReadOnly AllowedKeys As String = _
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,"
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case e.KeyChar
Case Convert.ToChar(Keys.Enter) ' Enter is pressed
' Call method here...
Case Convert.ToChar(Keys.Back) ' Backspace is pressed
e.Handled = False ' Delete the character
Case Convert.ToChar(Keys.Capital Or Keys.RButton) ' CTRL+V is pressed
' Paste clipboard content only if contains allowed keys
e.Handled = Not Clipboard.GetText().All(Function(c) AllowedKeys.Contains(c))
Case Else ' Other key is pressed
e.Handled = Not AllowedKeys.Contains(e.KeyChar)
End Select
End Sub