Skip to content

Instance Management

Alec Musasa edited this page Aug 9, 2021 · 2 revisions
#include <liblec/lecui/instance.h>

Preventing Multiple Instances

To prevent multiple instances of the same application is very simple in lecui. All we have to do is make an in-class instance manager variable. The instance manager class takes two parameters, a reference to the form and a GUID. Each application must have a unique GUID. There are various ways of generating a GUID, e.g. from the Tools menu in Visual Studio.

#include <liblec/lecui/instance.h>
using namespace liblec;

class sample_form : public lecui::form {
    lecui::instance_manager _instance_man{ *this, "{D39C94B6-360A-490E-864D-03273345447D}" };

public:
    sample_form() : form("Sample Form") {}
};

int main() {
    sample_form form;
    std::string error;
    if (!form.create(error))
        form.message(error);
    return 0;
}

Things to note:

  • All we need to do to prevent multiple instances of the application is to declare an instance management class;
  • When a new instance is attempted it re-directs to the existing instance instead; bringing the existing form to the foreground and termination the creation of the new form;
  • The .create() method in the form class returns true as soon as the existing instance is called;
  • A lecui application can only be uniquely identified using the instance GUID, not by having the same name, the same code, or the same icon :)

Inter-process Communication

It is possible for running lecui apps to communicate to each other as long as they know each other's GUID. This is done through the .send_data() method in the instance manager class. The .send_data() method takes four parameters:

  • the GUID of the receiving application;
  • the data to be sent. This can be any format, e.g. a serialized data structure;
  • the time-out for the send operation. If the data is not successfully sent within this time-frame the method returns an error. This is essential to avoid indefinite blocking and to prevent deadlocks;
  • a reference to the error string. Error information is written back to this parameter when the method returns false.

Here is an example of how we would send data to an application whose GUID is "{6F2EA5B2-4D56-4A03-A7FE-641057D63891}":

std::string error;
if (!_instance_man.send_data("{6F2EA5B2-4D56-4A03-A7FE-641057D63891}",
    "This is a simple message", 500, error)) {
    message("Sending data failed: " + error);
}

The receiving application received the handler passed into the .on_receive_data() method in the form class.