KeyDown Event Firing in VB.Net When No Key Is Pressed
I am running VS 2008 and building my app on a Windows 7 box. The main form/window has a KeyDown
event handler as follows in it:
Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
MsgBox("control = " + e.Control.ToString + ", shift = " + e.Shift.ToString + ", e.Keycode = " + e.KeyCode.ToString)
When I build it and run it within VS it seems to run fine. The messagebox appears with the state of the control and shift keys along with the key code of the key I pressed. However, if I take the executable and run it on an XP box (both using .Net Runtime 3.5) as soon as the main form opens, the messagebox appears. Basically the "KeyDown" event seems to be firing without any keys being pressed. The messagebox comes back with: "control = False, shift = False, e.Keycode = None"
.
How is this possible? How can the keyDown
event be fired when no keys have been pressed (as is confirmed by the output contained in the messagebox?)
Any suggestions on what might be happening or how I can diagnose this on the XP box since it does not have Visual Studio on it?
Update I tried creating a brand new project where there is only "form1" and the only code behind this is the keyDown event handler. It just opens a blank window and pops up the message box if a key is pressed. It worked as expected on the Win 7 box but w开发者_如何转开发hen I moved the executable to the XP box, it immediately popped open the messagebox without pressing a key. Very strange.
The best way of doing this is to override ProcesCmdKey for your form, like the example below:
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, keyData As System.Windows.Forms.Keys) As Boolean
MessageBox.Show("Pressed" & Convert.ToChar(keyData))
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
Regards.
Sometimes .net controls fire on form or app initialization. Microsoft says this is "by design." If you have a problem, you can use a flag variable to abort any processing in the keydown handler until the form is loaded.
精彩评论