6

Anyone have any tips/code snippets for preventing more than one copy of a custom X++ form from being opened at a time?

Best case: Attempt to open another copy of the form, and the original gains focus

Acceptable: User receives a notice that the form is already open

Jan B. Kjeldsen
  • 17,339
  • 5
  • 30
  • 49
Brad
  • 1,337
  • 5
  • 30
  • 60

2 Answers2

10

you could insert the code below into the form's init method. If you have any questions to the code don't hesitate to ask!

public void init()
{
    #define.CACHE_OWNER        ('MyForm')
    #define.CACHE_KEY_INSTANCE ('Instance')

    FormRun existingForm()
    {
        ;

        if (infolog.globalCache().isSet(#CACHE_OWNER, #CACHE_KEY_INSTANCE))
        {
            return infolog.globalCache().get(
                #CACHE_OWNER, #CACHE_KEY_INSTANCE);
        }
        return null;
    }

    void registerThisForm()
    {
        ;

        infolog.globalCache().set(#CACHE_OWNER, #CACHE_KEY_INSTANCE, this);
    }

    boolean isAlreadyOpened()
    {
        ;

        return existingForm() ? !existingForm().closed() : false;
    }

    void activateExistingForm()
    {
        ;

        existingForm().activate(true);
    }
    ;

    super();
    if (isAlreadyOpened())
    {
        activateExistingForm();
        this.close();
    }
    else
    {
        registerThisForm();
    }
}
DAXaholic
  • 28,212
  • 5
  • 58
  • 67
  • 1
    This works nicely. I did have to change the activate method to element.existingForm().setActive(); The activate() command did not bring the original form to the front. Thanks so much! – Brad Oct 18 '13 at 15:47
0

Add the following code to the init method of the form as follows. No other changes are required.

public void init()
{
    #define.CACHE_OWNER('MyForm')
    int hWnd;

    super();

    if (infolog.globalCache().isSet(#CACHE_OWNER, curUserId()))
    {
        hWnd = infolog.globalCache().get(#CACHE_OWNER, curUserId());
    }

    if (WinApi::isWindow(hWnd))
    {
        element.closeCancel();
        WinAPI::bringWindowToTop(hWnd);
    }
    else
    {
        infolog.globalCache().set(#CACHE_OWNER, curUserId(), element.hWnd());
    }
}
10p
  • 4,551
  • 18
  • 26