Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
VB.NET
Imports System.Runtime.InteropServices

 <dllimport("user32.dll", setlasterror:="True)">
 Private Shared Function SendInput(
     ByVal nInputs As UInteger,
     ByVal pInputs As INPUT(),
     ByVal cbSize As Integer
 ) As UInteger
 End Function

 ' Define the INPUT structure
 <structlayout(layoutkind.sequential)>
 Structure INPUT
     Public type As Integer
     Public ki As KEYBOARDINPUT
 End Structure

 ' Define the KEYBOARDINPUT structure
 <structlayout(layoutkind.sequential)>
 Structure KEYBOARDINPUT
     Public wVk As UShort
     Public wScan As UShort
     Public dwFlags As UInteger
     Public time As UInteger
     Public dwExtraInfo As IntPtr
 End Structure

 ' Constants for input type and key events
 Const INPUT_KEYBOARD As Integer = 1
 Const KEYEVENTF_KEYUP As UInteger = &H2

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
     ' Simulate pressing the space bar using SendInput
     SendSpaceBar()
 End Sub

 Private Sub SendSpaceBar()
     Dim input As New INPUT()
     input.type = INPUT_KEYBOARD
     input.ki.wVk = &H20 ' VK_SPACE code for space bar

     ' Press the space bar
     SendInput(1, {input}, Marshal.SizeOf(GetType(INPUT)))

     ' Release the space bar
     input.ki.dwFlags = KEYEVENTF_KEYUP
     SendInput(1, {input}, Marshal.SizeOf(GetType(INPUT)))
 End Sub


What I have tried:

I am using vb to write the script.

I want write the code to control chrome and edge broswer space bar but my code no working.

can help me take a look thank you.
Posted
Updated 2-Feb-24 4:55am
v2
Comments
Richard MacCutchan 2-Feb-24 5:15am    
You need to explain exactly what you expect to happen here, and what actually happens. You also need to check the return value from your call to SendInput to see whether it succeeded or not. Also take a look at SendInput function (winuser.h) - Win32 apps | Microsoft Learn[^] for an example of how it should be done.

1 solution

Erm ... you did read what SendInput does, right? It feeds keyboard and mouse info into the appropriate queues - which means that are extracted by the active application.
Which since you just pressed a mouse button isn't Chrome: it's your app.

You need to send them to a specific window (try FindWindow and SetForegroundWindow) and then use SendKeys to send the space to Chrome.
No guarantees it'll work, but ...
 
Share this answer
 
Comments
Member 12859920 4-Feb-24 20:42pm    
@OriginalGriff whcih mean i need add key control on my code and call it to press space bar?
OriginalGriff 5-Feb-24 1:33am    
No, read what I said again ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900