AlertWindow returns immediately

I want an alertwindow to pop up when the user clicks on a button. The user then has the option to cancel or confirm the button click. But the alertwindow immediately returns 0 when it pops up. I need it to wait for the user to click a button in the alertwindow. How can i achieve that?

Here is my code:

std::cout << juce::AlertWindow::showOkCancelBox(juce::AlertWindow::WarningIcon, "Confirm disconnect", "Are you sure you want to disconnect? \n\nThis will kill all the audio that is controlled by OSC.", "Disconnect", "Cancel", nullptr, nullptr) << std::endl;

Do you have the modal loops macro defined to 1? I think it’s something like JUCE_MODAL_LOOPS_ALLOWED

Actually its JUCE_MODAL_LOOPS_PERMITTED=1

Create a new class derived from AlertWindow

class DisconnectWindow : public AlertWindow
{
public:
    DisconnectWindow()
        : AlertWindow ("Confirm Disconnect", "Are you sure you want to disconnect?", AlertIconType::WarningIcon)
    {
        addButton("Save", 1);
        addButton ("Cancel", 0);
    }
};

and then:

DisconnectWindow disconnectWindow; 
if disconnectWindow.runModalLoop() == 1) // if they picked 'ok'
{
    // your code here
}

Edit: you’ll want a custom alert window to better control the look and feel

It’s actually JUCE_MODAL_LOOPS_PERMITTED=1, but I believe that this behaviour is no longer recommended, especially for plugins, and the advice has been to write your code to use Asynchronous AlertWindows and Dialogs, and callbacks to complete the operation that you are requesting user input on.

Yes, I know, I personally would never use a modal window like this person is trying to ¯\(ツ)

Thanks for your help.

I want to do it the right way. How can i create my own callback for alertWindows? There doesn’t seem to be a listener class for alertWindows in JUCE.

Usually the pattern looks like:

void callBackFunc (int result)
{
  // do stuff...
}

auto opts = juce::MessageBoxOptions().withTitle ("Foo").withMessage ("Your message here");

juce::AlertWindow::showAsync (opts, [](int res){ callBackFunc (res); });
1 Like

Thanks it’s working now :slight_smile:

1 Like