How to link a function to a Button (GUI)?

 

Hi,

I'm making a GUI for my EA. 

I'm using this code https://docs.mql4.com/constants/objectconstants/enum_object/obj_button

What I want to do is link a function to a button, so that when I press it, the function gets called. My ugly workaround as of now is: 

void OnTick()
{
        if (ObjectGetInteger(0, "Button", OBJPROP_STATE) && released) {
                Print("I have been pressed");
                released = false;
                pressed = true;
                Sleep(200);
        }
        else if (!ObjectGetInteger(0, "Button", OBJPROP_STATE) && pressed) {
                Print("I have been released");
                released = true;
                pressed = false;
                Sleep(200);
        }
}

 

 Is there a more elegant way to do it? Can I separate the GUI interaction from the OnTick() function? (For example, in the Unity 3D engine, there is the Update() function and the OnGUI() function).

Thank you. 

 

OnTimer()

OnChartEvent() 

 

And do not forget unpress button

 if(ObjectGetInteger(0,"BUY_button",OBJPROP_STATE))
{ 
ObjectSetInteger(0,"BUY_button",OBJPROP_STATE,false); 
 

Thanks for answering, eevviill, got it working!

What seems to be not working now is the button unpressing. Shouldn't I be setting the state to true? Anyways, its not working with either.

Ideally, what I would like is that everytime I press the button, the message got printed (and the button to look always ready to be pressed). Right now, it is working like a switch instead of like a button.

Current code: 

void OnChartEvent(const int id, const long& lparam, const double& dparam, const string& sparam)
{
    if (id == CHARTEVENT_OBJECT_CLICK) // Assume there is only this button
        if (ObjectGetInteger(0, "Button", OBJPROP_STATE)) {
            Print("I have been pressed");
            Sleep(100);
            ObjectSetInteger(0, "BUY_button", OBJPROP_STATE, false); // Whether true or false, not working
        }
}
 
Flood19:

Thanks for answering, eevviill, got it working!

What seems to be not working now is the button unpressing. Shouldn't I be setting the state to true? Anyways, its not working with either.

Ideally, what I would like is that everytime I press the button, the message got printed (and the button to look always ready to be pressed). Right now, it is working like a switch instead of like a button.

Current code: 

You make unpress to another name of button

BUY_button 

 

And OnChartEvent and OnTimer 

do not works in tester. Just for information. 

Reason: