I'm trying to send a key down and up message via SendMessage instead of SendKeys -- I need to send the key when another application has focus, so SendKeys won't do. I've read prior questions on this. I can't seem to get any of the solutions offered to work. Here is some code illustrating the problem. I can't figure out why it won't work.
Public Class Form2
Declare Auto Function FindWindowEx Lib "user32" (ByVal hwndParent As IntPtr, ByVal hwndChildAfter As IntPtr, ByVal lpszClass As String, ByVal lpszWindow As String) As IntPtr
Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal uMsg As Integer, ByVal wParam As Integer, ByVal lParam As String) As Integer
Declare Auto Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal uMsg As Integer, ByVal wParam As Integer, ByVal lParam As UInt32) As Integer
Private Sub SendMessageToNotepad()
Dim lParamDown1, lParamUp1, lParamDown2, lParamUp2 As UInt32
Dim repeatCount As UInt32 = 1, scanCode As UInt32 = 0, extended As UInt32 = 0, context As UInt32 = 0,
previousState As UInt32 = 0, transition As UInt32 = 0
' TRYING TO SET THE LPARAM FOR BOTH THE KEYUP AND KEYDOWN COMMANDS
scanCode = &H53
lParamDown1 = repeatCount Or (scanCode << 16) Or (extended << 24) Or (context << 29) Or (previousState << 30) Or (transition << 31)
transition = 1
previousState = 1
scanCode = &H53
lParamUp1 = repeatCount Or (scanCode << 16) Or (extended << 24) Or (context << 29) Or (previousState << 30) Or (transition << 31)
Dim notepads() As Process = Process.GetProcessesByName("notepad")
If notepads.Length = 0 Then
Return
End If
Dim child As IntPtr = FindWindowEx(notepads(0).MainWindowHandle, New IntPtr(0), "Edit", Nothing)
If notepads(0) IsNot Nothing Then
' SEND THE KEYDOWN MESSAGE (i.e. &H100) (VK_S = &H53)
SendMessage(child, &H100, &H53, lParamDown1)
' SEND THE KEYUP MESSAGE (i.e. &H100) (VK_S = &H53)
SendMessage(child, &H101, &H53, lParamUp1)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SendMessageToNotepad()
End Sub
End Class