Bloggging about .NET tips, tricks, and so much more...!

Wednesday, November 21, 2007

Module modKeys: Easy way to manipulate key event using this class module in VB .NET 2005

Module modKeys
Public Declare Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)
Public Declare Function MapVirtualKey Lib "user32" Alias "MapVirtualKeyA" (ByVal wCode As Integer, ByVal wMapType As Integer) As Integer

Public Const KEYEVENTF_KEYDOWN As Short = &H0S
Public Const KEYEVENTF_KEYUP As Short = &H2S

Public Enum EnumCharType
vbAlphaOnly = 0 'type for Characters only
vbNumericOnly = 1 'type for numeric only
vbAlphanumeric = 2 'Allow Alphanumeric
vbOnListOnly = 3
End Enum

Public Enum EnumKeyExec
vbEnterOnly = 0 'this would only allow enter key
vbBackSpaceOnly = 1 'allow backspace only
vbSpaceOnly = 2 'allow space only
vbEnterBackSpace = 3 'allow both backspace and enter
vbEnterSpace = 4 'allow enter and space
vbSpaceBackSpace = 5 'allow space and backspace
vbDefaultKeys = 6 'allow space,enter and backspace
End Enum

Public Sub AutoShiftTab()
keybd_event(System.Windows.Forms.Keys.ShiftKey, MapVirtualKey(System.Windows.Forms.Keys.ShiftKey, 0), KEYEVENTF_KEYDOWN, 0)
keybd_event(System.Windows.Forms.Keys.Tab, MapVirtualKey(System.Windows.Forms.Keys.Tab, 0), KEYEVENTF_KEYDOWN, 0)
keybd_event(System.Windows.Forms.Keys.ShiftKey, MapVirtualKey(System.Windows.Forms.Keys.ShiftKey, 0), KEYEVENTF_KEYUP, 0)
End Sub

End Module



SAMPLE CODE:
Public Class Form1

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
'//-ALPHA NUMERIC with special characer " .?/@#"
e.KeyChar = ChrW(modKeys.Keyed(AscW(e.KeyChar), EnumCharType.vbAlphanumeric, EnumKeyExec.vbEnterBackSpace, True, "[ .?/_]"))
Select Case AscW(e.KeyChar)
Case System.Windows.Forms.Keys.Return
AutoTab() '//-focused on next tab order
End Select
End Sub

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
Select Case e.KeyCode
Case System.Windows.Forms.Keys.Down
AutoTab() '//-focused on next tab order
Case System.Windows.Forms.Keys.Up
AutoShiftTab() '//-focused on previous tab order
End Select
End Sub

Private Sub TextBox4_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox4.KeyPress
'//-SELECTED CHARACTER
e.KeyChar = ChrW(modKeys.Keyed(AscW(e.KeyChar), EnumCharType.vbOnListOnly, EnumKeyExec.vbEnterBackSpace, True, "[RrUuBbEeNn]"))
End Sub

End Class

No comments:

PRC Board Exam Results

Feeds from Jehzlau Concepts