Friday, April 29, 2011

Programmically toggling capslock button

VB.NET doesn’t contain any function through which we can On/Off capslock button in the keyboard. VB.NET has one function called My.Computer.Keyboard.CapsLock but it is readonly so we cannot change it. Capslock key also cannot be toggled by using SendKeys,Send() method. So only way to toggle the capslock key is by using WinAPIs. There is a function called keybd_event which can toggle the capslock key

Private Declare Sub keybd_event Lib "user32" (ByVal key As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)

    Private Sub ToggleCapslock()
        keybd_event(Keys.Capital, 0, 0, 0)
        keybd_event(Keys.Capital, 0, &H2, 0)
    End Sub

In the above example we have called the keybd_event function twice. First for Keydown and second time for KeyUp (&H2 is value for KeyUp). If we want the code to work only to set capslock Off then we can change the code as below

   Private Sub SetCapslockOff()
If My.Computer.Keyboard.CapsLock = True Then
keybd_event(Keys.Capital, 0, 0, 0)
keybd_event(Keys.Capital, 0, &H2, 0)
Else
'Already off
End If
End Sub

Sunday, April 10, 2011

Tab key work as an Enter key in Datagridview

To make the Tab key work as Enter key, we have to inherit DataGridView controls and override two methods ProcessDataGridViewKey and ProcessDialogKey. In both the methods if the user has click Tab then we have to ProcessEnterKey of Datagridview.

Public Class NewDataGridView
Inherits DataGridView

Protected Overrides Function ProcessDataGridViewKey(ByVal e As System.Windows.Forms.KeyEventArgs) As Boolean
If e.KeyCode = Keys.Tab Then
Me.ProcessEnterKey(e.KeyData)
Return True
End If
Return MyBase.ProcessDataGridViewKey(e)
End Function

Protected Overrides Function ProcessDialogKey(ByVal keyData As System.Windows.Forms.Keys) As Boolean
If keyData = Keys.Tab Then
Me.ProcessEnterKey(keyData)
Return True
End If
Return MyBase.ProcessDialogKey(keyData)
End Function
End Class