KeyUp event works in first winform, but not in second, why? - vb.net

I have a winform program where I am trying to include PF functionality in tandem with button/mouse-click functionality. On the first screen that opens in the application, the keyup event works. I changed the KeyPreview property to True and wrote the following code:
Private Sub Vehicle_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyUp
If e.KeyCode = Keys.F1 Then
CarrierOn = True
Call Display_CarrierDetail_Screen()
ElseIf e.KeyCode = Keys.F9 Then
Call Display_History_Screen()
ElseIf e.KeyCode = Keys.F6 Then
Call Display_County_Screen()
ElseIf e.KeyCode = Keys.F5 Then
Call Instant_Observation("Vehicle")
End If
End Sub
The above works.
However, on opening the second form, I wrote very similar code, also changed that form's keypreview property to True, and tested the PF key - nothing happens.
Why would it work on the first form, but not on the second? The second does have the focus when I am pressing the PF key.
Thank you, laurie

Related

Why does windows play a beep sound on KeyDown, but not on DoubleClick?

I hope this is going to be a real quick question:
I have a TreeView on a Windows form.
I run this code to open directories, displayed in a tree view:
Private Sub OpenFolder()
Try
System.Diagnostics.Process.Start(SelectedDir)
Catch ex As Exception
MessageBox.Show("Mappen " & SelectedDir & " kan ikke åbnes!")
End Try
End Sub
When I call OpenFolder() from the KeyDown event:
Private Sub TreeViewDir_KeyDown(sender As Object, e As KeyEventArgs) Handles TreeViewDir.KeyDown
If e.KeyCode = Keys.Enter Then
OpenFolder()
e.SuppressKeyPress = True
ElseIf e.KeyCode = Keys.Delete Then
DeleteFolder()
e.SuppressKeyPress = True
End If
End Sub
..I get a windows error sound. But no error message. What is driving me up the walls, is that this sub fires the function without any problems at all.
Private Sub TreeViewDir_DoubleClick(sender As Object, e As EventArgs) Handles TreeViewDir.DoubleClick
OpenFolder()
End Sub
The error sound plays when the folder opens, but again, only on KeyDown. Can someone tell me why this happens only on the KeyDown event and what I'm doing wrong here?
First, let me point out that your OpenFolder() method isn't responsible for that beep sound, the KeyPress event is. This is a standard behavior of Windows when a key is pressed where it has no job to do.
Now, setting SuppressKeyPress to true, should, in fact, prevent the KeyPress event from firing and therefore, no beep sound should be played. However, in some cases when you execute some code in the KeyDown event, it takes time for the keystroke to be suppressed and therefore causing the beep sound.
To get around this, you can simply subscribe to the KeyPress event and set e.Handled to true:
Private Sub TreeViewDir_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TreeViewDir.KeyPress
If e.KeyChar = ChrW(Keys.Enter) Then e.Handled = True
End Sub
Another solution, if you don't want to use KeyDown, is to allow some time for the keystroke to be suppressed, by delaying the execution of your method:
Private Async Sub TreeViewDir_KeyDown(sender As Object, e As KeyEventArgs) Handles TreeViewDir.KeyDown
' ^^^^^ ⟸ Don't forget the Async keyword.
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True ' This is first
Await Task.Delay(100) ' Followed by a small delay
OpenFolder() ' Then call the method.
End If
End Sub

Why DateTimePicker won't trigger keyDown and KeyPress events with the tab key?

Fellows, I am having this problem - the DateTimePicker won't trigger KeyDown and KeyPress events with the tab key (other keys are working fine, and the keyUp event as well, although it triggers after "arriving" at the DateTimePicker after pressing tab at the previous control focused). I'm using .net 4.6.1, Visual Basic and VS 2017.
What I'm trying to do -> Go to month and year directly on DateTimePicker in C# (Go to month and year directly on DateTimePicker)
Code I'm using:
Private Sub DateTimePicker1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DateTimePicker1.KeyDown
If e.KeyCode = Keys.Tab Then
e.Handled = True
MsgBox("TAB DOWN")
End If
End Sub
Private Sub DateTimePicker1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles DateTimePicker1.KeyPress
e.Handled = True
MsgBox("tab press")
End Sub
Private Sub DateTimePicker1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DateTimePicker1.KeyUp
If e.KeyCode = Keys.Tab Then
MsgBox("TAB UP")
e.Handled = True
End If
End Sub
Any clues?
The Tab key is used for navigation. Moving the focus from one control to another. So your KeyDown event handler can never see it, the keystroke is intercepted and used before that. You could subscribe the PreviewKeyDown event and set the e.IsInputKey = true as a workaround, check the MSDN sample code in the linked article for code.
But it is the wrong event to use anyway, you'd still want this to work when the user changes focus with the mouse instead of the keyboard. So use the Enter event instead.
Do beware that both approaches have the same problem, the focus might already be on the month part from previous usage of the control so now your code will incorrectly move it to the year part. And you can't find out what part has the focus, that is up a creek without a good paddle. A very ugly workaround for that is to change the Format property, and back, that forces the control to re-create the control window and that always resets the focus. Use BeginInvoke() to run that code. Perhaps more constructively, consider to just not display the day if you are only interested in month+year, CustomFormat property.
Sample code that implements the focus hack:
Private Sub DateTimePicker1_Enter(sender As Object, e As EventArgs) Handles DateTimePicker1.Enter
Me.BeginInvoke(
New Action(Sub()
'' Hack to reset focus
DateTimePicker1.Format = DateTimePickerFormat.Long
DateTimePicker1.Format = DateTimePickerFormat.Short
DateTimePicker1.Focus()
SendKeys.Send("{Right}")
End Sub))
End Sub
It's not the right answer to this question, although it helps as well. If you want to just make the tab behave as the right key when inside a DateTimePicker, a good (sketchy) way to do is:
Private i = 2
Protected Overrides Function ProcessTabKey(ByVal forward As Boolean) As Boolean
Dim ctl As Control = Me.ActiveControl
If ctl IsNot Nothing AndAlso TypeOf ctl Is DateTimePicker And i <> 0 Then
SendKeys.Send("{Right}")
i -= 1
Return True
End If
i = 2
Return MyBase.ProcessTabKey(forward)
End Function
You need to override ProcessCmdKey function
Private isTab As Boolean = False
Private isShiftTab As Boolean = False
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
If keyData = Keys.Tab Then
isTab = True
'Do something with it.
Else
isTab = False
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function

how to create button shortcuts in vbnet

I tried creating keyboard shortcuts for my buttons.
Here is my code
Private Sub form_main_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If Keys.ControlKey + Keys.N Then
'btn_add.PerformClick()
addentry()
ElseIf Keys.ControlKey + Keys.E Then
'btn_edit.PerformClick()
editentry()
End If
End Sub
The problem is even when I press other buttons the function is still called. I also tried using form keydown property but the result is still the same.
additional info:
the functions addentry and editentry will just call the form_addedit
btn_add will call for addentry
btn_edit will call for editentry
First of all Keys.*** is just an enumeration. Every entry in it is just a number representing a key code. So you are currently just adding numbers together.
Keys.ControlKey is 17 and Keys.N is 78, so you're literally writing:
If 17 + 78 Then
Which will always return True because it's greater than 0.
To do what you ask you must check which key was pressed by checking the event arguments (EventArgs) passed to the event.
But since you are using the KeyPress event you cannot get the key enumeration out of the event args, so I recommend you to use the KeyDown event instead.
Private Sub form_main_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.Control = True AndAlso e.KeyCode = Keys.N Then
addentry()
ElseIf e.Control = True AndAlso e.KeyCode = Keys.E Then
editentry()
End If
End Sub
If you put an ampersand in the .Text property of the button, Alt+key will fire the button, for example B&utton1 will fire with Alt+u.

Multiple Keyboard Shortcuts

I am using the following code to try and get Ctrl+S to press a toolstrip button:
Private Sub take_register_KeyDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.S And Keys.Control Then
ToolStripButton20.PerformClick()
End If
End Sub
I am a newbie at this, so I dont understand millions of lines of coding, so can you please keep it as simple as possible :-) .
Total guesswork here since there is no actual question. First, in order to get something like that work, you need to set KeyPreview = True for the form. Next, you probably want to use the KeyDown event instead of KeyPress:
Private Sub Form1_KeyDown(...)
' when possible use AndAlso for speed and to avoid some errors in
' some situations. if e.Control is False, the second part wont be evaluated.
If e.Control AndAlso e.KeyCode = Keys.S Then
ToolStripButton20.PerformClick()
End If
End Sub
To repeat: you can simply assign a shortcut key combo to the menu object in the designer and let .NET do all the work. ...and I don't know where "multiple" comes in to play unless Ctrl+S counts as multiple somehow.

Making a VB.net winform button look pressed from code behind

I've got a basic VB.net 2.0 application together in VisualStudio 2005.
Within a form, I've tied [enter] in several text boxes to a button. What I'd like to do is "press" the button from getField_KeyDown() to give the user a visual indication of what's happening.
With the code below, the button click work is done but the button's look doesn't change and the user is left without feedback.
Private Sub getField_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtGetKey.KeyDown
If e.KeyCode = Keys.Enter Then
e.Handled = True
Call btnGet.PerformClick()
End If
End Sub
How can I make the button looked pressed while the btnGet.PerformClick() work is being done?
You can make a checkbox and set the appearance to a button.
chkCheck.Appearance = Appearance.Button
You can also set this in the design mode.
And it behaves just the same as a normal checkbox. So you can assign a key pressed to the state of the checkbox.
You want to set the FlatStyle of the button. So your code will look like this:
Private Sub getField_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtGetKey.KeyDown
If e.KeyCode = Keys.Enter Then
e.Handled = True
btnGet.FlatStyle = FlatStyle.Flat
End If
End Sub
This will change the button appearance - Don't forget to change it back to FlatStyle.Standard