Your code is incorrect, as Abbas already pointed out in his answer. You have to call the shared Send
method of the SendKeys
class, like so:
Imports System.Windows.Forms
Public Class Form1
Private Sub TextBox2_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles TextBox2.KeyDown
If (e.KeyCode = System.Windows.Forms.Keys.Down) Then
SendKeys.Send("{tab}")
End If
End Sub
End Class
But that will still not solve your problem, because SendKeys
is not available in the Compact Framework. If you really need this functionality (and legitimate uses are, in my experience, quite rare), then you will need to do write the code manually that does the heavy lifting.
You have a couple of options:
You can P/Invoke the
SendInput
function, along with the required data structures, and then call this from your code. This function injects the specified input (in this case, you will want keyboard input) into the system's input stream. It is worth nothing that this is exactly that theSendKeys.Send
method uses in modern versions of the framework.Examples of how to declare and call this function are all over the web. A simple search should turn up everything you need, no need for me to reproduce it all here. pinvoke.net is a good place to start—sometimes their more obscure declarations are erroneous, but that's unlikely with something as common as
SendInput
. This answer has done the copying and pasting for you already, you just need to convert it to VB.NET. Simple enough, or there are free automatic translators available.When using that sample code, just make sure to change the
DllImport
location fromuser32.dll
(where the function is located on desktop versions of Windows) tocoredll.dll
(where the code is located on mobile versions).In Windows CE, you also have the
PostKeybdMessage
function that can be P/Invoked in a similar manner. This is probably simpler to declare and use thanSendInput
, but it is somewhat more limited in what it can do. It posts keyboard messages directly to the specified window, rather than adding them to the system input stream. However, in most cases, this is exactly what you want.<DllImport("coredll.dll", SetLastError := True)> _ Shared Function PostKeybdMessage(ByVal hWnd As IntPtr, _ ByVal vKey As UInteger, _ ByVal flags As UInteger, _ ByVal cCharacters As UInteger, _ ByVal pShiftStateBuffer As UInteger(), _ ByVal pCharacterBuffer As UInteger()) As Boolean End Function
You will also find suggestions various places online to P/Invoke the
keybd_event
function.Resist the temptation—as the linked official documentation indicates, it is obsolete and has been superseded by
SendInput
. The simplicity ofkeybd_event
looks appealing, but it will just get you into trouble. The inability to test for errors is a major drawback. The last time anyone had to usekeybd_event
was on Windows 95.