How to press keys with `enigo` in rust?

There is a test.json:


The first element is start time (millisecond).
The second element is the length of time (millisecond).
The third element is key,1\2\3\4 represent a\b\c\d respectively.

I want to press the corresponding keys when the start time reaches the value of the first element, and keep the length of the second element.

Take the first group of data as an example:
When the time comes to 1000 milliseconds, press key 'a' for 800 milliseconds.

I prepare to use crate delay_timer, enigo, serde_json,and below is my code:

There is only a little custom code. Search with the keyword Here is my code start. The other code is template from [delay_timer][1] example.


delay_timer = "0.10.1"
enigo = "0.0.14"
serde_json = "1.0"
anyhow = "1.0.51"
smol = "1.2.5"

use anyhow::Result;
use delay_timer::prelude::*;
use enigo::*;
use serde_json::{Result as SResult, Value};
use smol::Timer;
use std::fs::File;
use std::io::BufReader;
use std::thread;
use std::time::Duration;

fn main() -> Result<()> {
    let delay_timer = DelayTimerBuilder::default().build();
    // Create the task
    // A chain of task instances.
    let task_instance_chain = delay_timer

    // Get the running instance of task 1.
    let task_instance = task_instance_chain.next_with_wait().unwrap();

    // This while loop avoids removing the task before it completes
    while task_instance.get_state() != delay_timer::prelude::instance::COMPLETED {}

    // Remove task which id is 1.

fn build_task_async_print() -> Result<Task, TaskError> {
    let mut task_builder = TaskBuilder::default();

    let body = create_async_fn_body!({
        //Here is my code start
        let json_data = get_json().unwrap();

        for element in json_data.as_array().unwrap().iter() {
            Timer::after(Duration::from_millis(element[0].as_f64().unwrap() as u64)).await;
            println!("the value is: {}", element[0]);

            //How to complete the code that uses enigo to press the corresponding keys?
            let mut enigo = Enigo::new();
            thread::sleep(Duration::from_millis(element[1].as_f64().unwrap() as u64));
        //Here is my code end

    // Build the task and assign 1 to it

//Get json data from json file
fn get_json() -> SResult<Value> {
    let file = File::open("test.json").expect("file should open read only");
    let reader = BufReader::new(file);
    let mut v: Value = serde_json::from_reader(reader)?;

How to complete the code that uses enigo to press the corresponding keys?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.