2.5. Sample Code: ListBoxExample.g

This tutorial demonstrates the list box.

Output

Code

/* All user scripts should derive from the base "Application" class */

require ("Application");
require ("WindowsSupport");

class ListBoxExample Application
{
    window;
}

// Fill the combo box with choices
method ListBoxExample.FillCombo(lb)
{
    local       current = lb.GetWindowText();
    
    // Clear the combo box if we need to.
    lb.Clear();
    lb.ResetContent();
    
    // Add some options to the combo box
    lb.AddString("String 1");
    lb.AddString("String 2");
    
    // If there was an existing choice, reselect it
    lb.SelectString(-1, current);
}

// This is called when the combo box is selected
method ListBoxExample.ComboSelected(lb)
{
    princ ("You selected ", lb.GetWindowText(), "\n");
}

/* Write the 'main line' of the program here. */
method ListBoxExample.constructor ()
{
    local   win = new GWindow();
    local   rect = CreateRect(10, 10, 400, 400);
    
    win.Create (0, rect, "ListBox Example", WS_OVERLAPPEDWINDOW, 0);
    win.MessageHandler (WM_DESTROY, `(!destroyed_p(@self) ? destroy(@self) : nil));
    .window = win;
    .window.SetBackground (0, GetSysColor (COLOR_3DFACE), 0);
    
    // ------- List box example starts here
    
    // Create a combo box.  Use CBS_* to set the options.  An editable combo
    // uses CBS_DROPDOWN.
    local   lb = win.CreateControl (GComboBox, 5, 5, 200, 20,
        "ExampleListBox", CBS_DROPDOWNLIST | CBS_SORT);
    
    // If the window has a different background, make sure the combo box
    // stays white.
    lb.SetChildBackground (0, GetSysColor (COLOR_WINDOW), 0);
    
    // If we want to fill the combo when the person drops it down, do this
    win.CommandHandler (CBN_DROPDOWN, lb, `(@self).FillCombo(@lb));
    // Otherwise we could just do this to fill it once at the start
    // .FillCombo(lb);
    
    // Trigger an event when the user selects an option
    win.CommandHandler (CBN_SELCHANGE, lb, `(@self).ComboSelected(@lb));

    // ------- List box example ends here
    
    win.ShowWindow (SW_SHOW);
}

/* Any code to be run when the program gets shut down. */
method ListBoxExample.destructor ()
{
    if (instance_p(.window))
        destroy (.window);
}

/* Start the program by instantiating the class. */
ApplicationSingleton (ListBoxExample);