Simulate input/Keyboard: Difference between revisions

m
→‎{{header|Wren}}: Added compilation hint for C program.
(→‎{{header|Commodore BASIC}}: Add implementation.)
m (→‎{{header|Wren}}: Added compilation hint for C program.)
 
(6 intermediate revisions by 5 users not shown)
Line 25:
=={{header|AutoHotkey}}==
Target may be externally created.
<langsyntaxhighlight AutoHotkeylang="autohotkey">run, cmd /k
WinWait, ahk_class ConsoleWindowClass
controlsend, ,hello console, ahk_class ConsoleWindowClass</langsyntaxhighlight>
 
=={{header|AutoIt}}==
Code assumes you're working on a windows box. Run() can use any program, and WinWaitActive() requires the title of the program as it will be when it opens.
<langsyntaxhighlight AutoItlang="autoit">Run("notepad")
WinWaitActive("Untitled - Notepad")
Send("The answer is 42")</langsyntaxhighlight>
 
It takes user input in variable using "input box"
and displays that in "message box"
<langsyntaxhighlight AutoItlang="autoit">$name="type your name here"
$name = InputBox("Name","Your name please ?",$name)
MsgBox(0,"Name","Your name is: "&$name)</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
EXEC KB executes the text file KB from disk as if you had typed everything that is in the KB text file. MON I will MONitor Input from disk.
<syntaxhighlight lang="basic"> 100 REM SIMULATE KEYBORD INPUT
110 GOSUB 170"OPEN&WRITE KB
120 PRINT "HOME:RUN140"M$"MARK
130 PRINT D$C$A$"EXEC"F$: END
140 INPUT "NAME? ";N$
150 PRINT "HELLO, "N$"!"
160 END
170 D$ = CHR$ (4):C$ = "CLOSE"
180 M$ = CHR$ (13):O$ = "OPEN"
190 F$ = "KB":A$ = F$ + M$ + D$
200 PRINT D$"MON I"M$D$O$;
210 PRINT A$C$A$"DELETE"A$O$;
220 PRINT A$"WRITE"F$: RETURN </syntaxhighlight>
 
{{Out}}
 
<pre>NAME? MARK
HELLO, MARK!
 
]</pre>
 
==={{header|Commodore BASIC}}===
 
Most of the logic here is dedicated to detecting which Commodore model the program is being run on, in order to use the correct addresses for the keyboard input buffer.
<langsyntaxhighlight lang="basic">100 : REM SIMULATE KEYBORD INPUT
110 GOSUB 170:REM DETERMINE MODEL/LOCATIONS
120 PRINT CHR$(147);"NAME? MARK";CHR$(19);
Line 61 ⟶ 84:
240 V=45:GOSUB 260:IF B=58 THEN NC=208:KB=842:RETURN:REM C-128
250 PRINT "UNKNOWN MODEL!":END
260 A=PEEK(V)+256*PEEK(V+1):B=PEEK(A+4):RETURN</langsyntaxhighlight>
 
{{Out}}
Line 79 ⟶ 102:
gcc -o simkeypress -L/usr/X11R6/lib -lX11 simkeypress.c
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
Line 192 ⟶ 215:
XCloseDisplay(dpy);
return 1;
}</langsyntaxhighlight>
 
 
{{libheader|Gadget}}
<p>Compile with ./ccpre.sh siminput . -c for testing with VALGRIND</p>
<p>Then, execute ./siminput</p>
<syntaxhighlight lang="c">
 
#include <gadget/gadget.h>
 
LIB_GADGET_START
 
Main
Enable_raw_mode();
int tecla=0;
int t=0;
while (tecla!=27 ){
while ( Kbhit() ){
tecla = Getch();
Disable_raw_mode();
/* para algunas teclas, imprimirá el código interno que maneja
Gadget para estos eventos, código que no es estándar */
printf("TECLA = %d\n",tecla);
Enable_raw_mode();
}
usleep(100);
++t;
if ( t==10000 ){
system("xdotool key Return");
}else if( t==11000 ){
// Mi teclado actual es del MacBook Pro.
// En otro tipo de teclado, el código puede cambiar.
// consulte X11/keysymdef.h para más informacion.
Key_put(KEYP_ENTER); //0xff8d);
 
}else if( t==12000 ){
Key_put(KEYP_LEFT);
 
}else if( t==13000 ){
Key_put(KEYP_RIGHT);
}else if( t==14000 ){
Key_put(KEYP_UP);
}else if( t==15000 ){
Key_put(KEYP_DOWN);
}else if( t==16000 ){
Key_put(KEYP_PAGEUP);
}else if( t==17000 ){
Key_put(KEYP_PAGEDOWN);
 
}else if( t==18000 ){
Key_put(KEYP_HOME);
}else if( t==19000 ){
Key_put(KEYP_END);
}else if( t==20000 ){
Key_put(' ');
}else if( t==21000 ){
Key_put(KEYP_BACKSP);
}else if( t==22000 ){
Key_put(KEYP_TAB);
}else if( t==23000 ){
Key_put(KEYP_DELETE);
 
}else if( t==24000 ){
Key_put_ctrl('a');
}else if( t==24100 ){
Key_put_ctrl('b');
}else if( t==24200 ){
Key_put_ctrl('w');
 
}else if( t==24300 ){
Key_put_shift('a');
 
}else if( t==24400 ){
Key_put_alt('j'); // esto no funciona en mi teclado
}else if( t>=25000 ){
Key_put(KEYP_ESCAPE);
}
}
 
// Put_kbd_text() reconoce estos caracteres: otros caracteres, el
// resultado puede ser indefinido.
 
Put_kbd_text("Hola mundo[](){},.:;-_=?$%&/#@! \t<cruel>\n Año 2023");
String read;
// si no se ha puesto nada en el buffer de entrada con Put_kbd_text(),
// read será NULL:
read = Read_typed_string();
Disable_raw_mode();
if ( read){
printf("\nTEXTO = %s\nChar = %d\n",read, read[strlen(read)-1]);
}
free(read);
End
 
</syntaxhighlight>
{{out}}
<pre>
$ ./siminput
TECLA = 13
TECLA = 13
TECLA = 1000
TECLA = 1001
TECLA = 1002
TECLA = 1003
TECLA = 1007
TECLA = 1008
TECLA = 1005
TECLA = 1006
TECLA = 32
TECLA = 127
TECLA = 9
TECLA = 1004
TECLA = 1
TECLA = 2
TECLA = 23
TECLA = 65
TECLA = 27
 
TEXTO = Hola mundo[](){},.:;-_=?$%&/#@! <cruel>
Año 2023
Char = 51
 
</pre>
 
=={{header|Clojure}}==
{{trans|Java}}
<langsyntaxhighlight Clojurelang="clojure">(import java.awt.Robot)
(import java.awt.event.KeyEvent)
(defn keytype [str]
Line 210 ⟶ 360:
(doto robot
(.keyPress (int upCh))
(.keyRelease (int upCh))))))))</langsyntaxhighlight>
 
=={{header|Go}}==
Line 220 ⟶ 370:
 
N.B. You may need to execute: 'sudo chmod +0666 /dev/uinput' first if running on Linux.
<langsyntaxhighlight lang="go">package main
 
import (
Line 248 ⟶ 398:
log.Fatal(err)
}
}</langsyntaxhighlight>
 
=={{header|GUISS}}==
 
<langsyntaxhighlight lang="guiss">Start,Programs,Accessories,Notepad,Textbox,Type:Hello World[pling]</langsyntaxhighlight>
 
=={{header|Java}}==
Line 260 ⟶ 410:
 
Keystrokes when this function is executed will go to whatever application has focus at the time. Special cases may need to be made for certain symbols, but most of the VK values in KeyEvent map to the ASCII values of characters.
<langsyntaxhighlight lang="java5">import java.awt.Robot
public static void type(String str){
Robot robot = new Robot();
Line 275 ⟶ 425:
}
}
}</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.awt.Robot
Line 298 ⟶ 448:
fun main(args: Array<String>) {
sendChars("dir") // runs 'dir' command
}</langsyntaxhighlight>
 
=={{header|LabVIEW}}==
Line 306 ⟶ 456:
This example implements limited capability of simulating input/Keyboard on Windows using standard library only. For better Windows support we can use [https://github.com/khchen/winim Winim] and [https://github.com/juancarlospaco/nim-xdo xdo] for Linux.
Current example will simulate keyboard input of typing Hello world to the current focused window.
<langsyntaxhighlight lang="nim">when defined(windows):
import winlean
else:
Line 387 ⟶ 537:
 
main()
</syntaxhighlight>
</lang>
Compile and run it by (assuming we have GNU C compiler):
<pre>nim c -r ourfile.nim</pre>
Line 400 ⟶ 550:
ocaml -I +Xlib Xlib.cma keysym.cma send_event.ml
 
<langsyntaxhighlight lang="ocaml">open Xlib
 
let () =
Line 504 ⟶ 654:
(* close connection to server *)
xCloseDisplay d;
;;</langsyntaxhighlight>
 
=={{header|Oz}}==
Line 510 ⟶ 660:
 
Oz' default GUI toolkit is based on Tk. So we can do the same thing as in Tcl:
<langsyntaxhighlight lang="oz">declare
[QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
Entry
Line 523 ⟶ 673:
{Delay 100}
{Tk.send event(generate Entry Key)}
end</langsyntaxhighlight>
 
This only works with internal windows.
Line 532 ⟶ 682:
Target may be externally created, but process must be able to open tty/pty for writing.
 
<langsyntaxhighlight lang="perl">$target = "/dev/pts/51";
### How to get the correct value for $TIOCSTI is discussed here : http://www.perlmonks.org/?node_id=10920
$TIOCSTI = 0x5412 ;
Line 540 ⟶ 690:
sleep(2);
foreach $a ( @c ) { ioctl(TTY,$TIOCSTI,$a); select(undef,undef,undef,0.1);} ;
print "DONE\n";</langsyntaxhighlight>
 
 
Line 550 ⟶ 700:
Target may be externally created.
 
<langsyntaxhighlight lang="perl">SendKeys("Hello, how are you?\n");</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include pGUI.e
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Simulate_keyboard_input.exw
string hw = "Look ma no hands! "
--</span>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- you'd better hope this sort of thing ain't possible in a browser!</span>
function timer_cb(Ihandle ih)
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
if length(hw) then
IupSetGlobalInt("KEY",hw[1])
<span style="color: #004080;">string</span> <span style="color: #000000;">hw</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Look ma no hands! "</span>
hw = hw[2..$]
else
<span style="color: #008080;">function</span> <span style="color: #000000;">timer_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
IupSetAttribute(ih,"RUN","NO")
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">hw</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
end if
<span style="color: #7060A8;">IupSetGlobalInt</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"KEY"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hw</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
return IUP_CONTINUE
<span style="color: #000000;">hw</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">hw</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
end function
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ih</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"RUN"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
IupOpen()
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
Ihandle txt = IupText("SIZE=170x10")
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
Ihandle dlg = IupDialog(txt,`TITLE="Simulate input", CHILDOFFSET=10x40, SIZE=200x80`)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
IupShow(dlg)
Ihandle hTimer = IupTimer(Icallback("timer_cb"), 250)
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
IupMainLoop()
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">txt</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"SIZE=170x10"</span><span style="color: #0000FF;">)</span>
IupClose()</lang>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">txt</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="Simulate input", CHILDOFFSET=10x40, SIZE=200x80`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">hTimer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupTimer</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"timer_cb"</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">250</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
Line 586 ⟶ 744:
in the following example. Keyboard input is simulated with the function 'enter'
to fill the login form's name and password fields.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/http.l" "@lib/scrape.l")
 
# Connect to the demo app at http://7fach.de/8080
Line 600 ⟶ 758:
(click "Spare Part") # Click on "Spare Part" article
(prinl (value 8)) # Print the price (12.50)
(click "logout") # Log out</langsyntaxhighlight>
{{out}}
<pre>12.50</pre>
Line 608 ⟶ 766:
The Start-Sleep CmdLet must be used because no application loads instantaneously. The -Milliseconds parameter should be
adjusted accordingly for every application.
<syntaxhighlight lang="powershell">
<lang PowerShell>
Add-Type -AssemblyName Microsoft.VisualBasic
Add-Type -AssemblyName System.Windows.Forms
Line 615 ⟶ 773:
[Microsoft.VisualBasic.Interaction]::AppActivate(“Calc”)
[System.Windows.Forms.SendKeys]::SendWait(“2{ADD}2=”)
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
{{libheader|AutoWin}}
 
<langsyntaxhighlight PureBasiclang="purebasic">If AW_WinActivate("Calc")
AW_SendKeys("123+3=")
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
Line 629 ⟶ 787:
{{libheader|AutoPy}}
 
<langsyntaxhighlight Pythonlang="python">import autopy
autopy.key.type_string("Hello, world!") # Prints out "Hello, world!" as quickly as OS will allow.
autopy.key.type_string("Hello, world!", wpm=60) # Prints out "Hello, world!" at 60 WPM.
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)</langsyntaxhighlight>
 
{{works with|Python|2.5+}}
Line 642 ⟶ 800:
Target may be externally created.
 
<langsyntaxhighlight Pythonlang="python">>>> import pyautogui
>>> pyautogui.typewrite('Hello world!') # prints out "Hello world!" instantly
>>> pyautogui.typewrite('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character
Line 651 ⟶ 809:
>>> pyautogui.press('left') # press the left arrow key
>>> pyautogui.keyUp('shift') # release the shift key
>>> pyautogui.hotkey('ctrl', 'shift', 'esc')</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket/gui
 
(define frame (new frame%
Line 677 ⟶ 835:
(send frame show #t) ; Shows the frame with a white canvas inside
(send canvas simulate-key (new key-event% (key-code #\k))) ; Sends the simulated key press (with a key-event% instance)
;outputs k</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 684 ⟶ 842:
Use libxdo bindings to send text / keystrokes to any application that will accept keystrokes from X11.
 
<syntaxhighlight lang="raku" perl6line>use X11::libxdo;
 
my $xdo = Xdo.new;
Line 714 ⟶ 872:
sleep .5;
$xdo.send-sequence($w, 'Return');
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 720 ⟶ 878:
{{works with|Personal REXX}}
Note: &nbsp; this REXX program &nbsp; ''only'' &nbsp; works with the above two REXXes.
<langsyntaxhighlight lang="rexx">/*REXX pgm shows how to use the REXX/PC PRESS cmd to simulate keyboard input.*/
 
call press 'This text will be put into a buffer as if it came from the keyboard'
 
/* [↑] text will be available for any program to use (including DOS).*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight><br><br>
 
=={{header|Rust}}==
Line 731 ⟶ 889:
{{libheader|AutoPilot}}
 
<langsyntaxhighlight Rustlang="rust">extern crate autopilot;
fn main() {
autopilot::key::type_string("Hello, world!", None, None, &[]);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight lang="scala">import java.awt.Robot
import java.awt.event.KeyEvent
 
Line 763 ⟶ 921:
}
keystroke(args(0))
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 770 ⟶ 928:
This only works with windows created by Tk;
it sends a single key "x" to the given window.
<langsyntaxhighlight lang="tcl">set key "x"
event generate $target <Key-$key></langsyntaxhighlight>
To send multiple keys, call repeatedly in order.
Alphabetic keys can be used directly as events, " " has to be mapped to "<space>".
<langsyntaxhighlight Tcllang="tcl">package require Tk
pack [text .t]
focus -force .t
foreach c [split "hello world" ""] {
event generate .t [expr {$c eq " "?"<space>": $c}]
}</langsyntaxhighlight>
Note also that the task on [[Keyboard macros#Tcl|keyboard macros]]
illustrates a very closely related method.
 
On Windows simulate pressing the Escape, Backspace etc keys
<langsyntaxhighlight lang="tcl">package require twapi
twapi::send_keys ({Esc})</langsyntaxhighlight>
 
=={{header|VBScript}}==
The keystrokes are sent to the active window.
 
<langsyntaxhighlight lang="vbscript">Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "{Down}{F2}"
WScript.Sleep 1000 ' one-second delay
WshShell.SendKeys "{Left}{Left}{BkSp}{BkSp}Some text here.~" ' ~ -> Enter</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 801 ⟶ 959:
<br>
As it's not currently possible for Wren-cli to access Xlib directly, we embed a Wren script in a C application to complete this task.
<langsyntaxhighlight ecmascriptlang="wren">/* simulate_input_keyboardSimulate_input_Keyboard.wren */
 
import "random" for Random
Line 960 ⟶ 1,118:
 
/* close connection to server */
xd.closeDisplay()</langsyntaxhighlight>
<br>
We now embed this Wren script in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Simulate_input_Keyboard.c -o Simulate_input_Keyboard -lX11 -lwren -lm */
<lang c>#include <stdio.h>
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 1,280 ⟶ 1,440:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "simulate_input_keyboardSimulate_input_Keyboard.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 1,296 ⟶ 1,456:
free(script);
return 0;
}</langsyntaxhighlight>
9,476

edits