How to use the button pressed and released events in egui?

This is easy to implement in C #, but in Rust, it seems difficult and the documentation is also difficult to understand.

are you familiar with how immediate mode GUI work? it's straight forward, but it's different from retained mode GUI.

basically, you use the clicked() method in your ui update code like this:

if ui.button("click me").clicked() {
    println!("button clicked");
}

there's an example in the document too:

This is just a simple click to trigger an event, of course it's not a problem, but what I need is to implement a way to keep running the tasks in the event while holding down the button, and stop executing the tasks in the event when releasing it.

Events like MouseDown and MouseUp

it depends how you implement the "task". because immediate mode GUI typically runs every frame, you can use is_point_button_down_on()

if ui.button("my button").is_pointer_button_down_on() {
    // still running
}

depending on your intended behavior, you might find drag_started() and drag_released() interesting too, you need to enable sensing drag for buttons, as by default buttons only sense click events.

let response = ui.add(Button::new("my button").sense(Sense::drag()));
if respnse.drag_started() {
    // start a background task
} else if response.drag_released() {
    // stop the task
}

for more complicated use cases, you may need to implement your own event detection logic. you get the bounding rectangle of the button, and read the input states,

let rect = ui.button("my button").rect;
ui.input(|input| {
    if input.pointer.button_pressed(PointerButton::Primary)
            && rect.contains(input.pointer.press_origin().unwrap()) {
        // mouse pressed this frame
    }
});

see

2 Likes

In C#:

private void button_RobotXZ_MouseDown(object sender, MouseEventArgs e)
 { 
          int JogMoveXZ = 1; 
          RobotJogMoving(JogMoveXZ); //robot x+ is running
}
private void button_RobotXZ_MouseUp(object sender, MouseEventArgs e) 
{ 
          int JogMoveXZ = 0; 
          RobotJogMoving(JogMoveXZ); //robot x+ is stop
}

ok, i will try.
thank you

as it turns out, drag_started and drag_released is like the mouse down and mouse up events, but by default not every widget will detect drag events, you need to manually enable the it for some widgets, including buttons.

I edited my previous comment.

1 Like

Thank you very much, Master.

This is precisely the difference between immediate mode and retained mode rendering. In immediate mode widgets cannot sent events to event listeners because there are no persistent widgets at all. The whole UI is transient, ephemeral, created anew on every frame, and thus you can just check what the current input state is in the code that creates the UI.