Control Methods

OLE automation methods are like member functions of C++ objects. For example, we might add a method named Beep() to the CONTROL project, making the computer beep. Using ClassWizard, methods are as easy to add to our control as properties were. To add the Beep() method, open ClassWizard and select the OLE Automation tab. Make sure that the control class, CControlCtrl, is selected in the Class Name box; click Add Method, opening the Add Method box, as shown in Figure 9.11.

Figure 9.11  Using the Add Method box, we add the Beep() method to our OCX control.

Type the name of this method, Beep, in the External Name box and select void in the Return Type drop-down listbox, indicating that we do not want to return any values from this function. If we had wanted to, we could have had our method return values such as long, short, or float by selecting them in this box. In addition, our method will not have any parameters passed to it. To receive parameters, we could type their names in the Name column of the Parameter List box (see Figure 9.11), and then select the parameter type in the drop-down listbox that appears in the Type column of the Parameter List box (we'll see how this works when we add a custom event next). Now click OK in the Add Method box, adding the Beep() method to CONTROL. Next, click the Edit Code button in ClassWizard, opening the new Beep() method:

void CControlCtrl::Beep() 
{
}

We'll have the computer beep when this method is invoked, so add this line of code:

void CControlCtrl::Beep() 
{
--> MessageBeep(MB_OK);
}

Now we've added a new method to our control. We can test this new method by inserting a control of the CONTROL type in the OLE control test container and selecting Invoke Methods in the test container's Edit menu, opening the Invoke Control Method box as shown in Figure 9.12.

Figure 9.12  Invoking our control's new method.

Our Beep() method is available for use; clicking Invoke calls the Beep() method and makes the computer beep. To reach the Beep() method from VBScript, we do just what you might expect; we call Ctrl1.Beep() (we've given our new control the ID Ctrl1).

<HTML>
<HEAD>
<TITLE>Control Page</TITLE>
</HEAD>
<BODY LANGUAGE = VBScript ONLOAD = "Page_Initialize">
<CENTER>
<H1>Control Page</H1>
</CENTER>
<!- control.ocx>
<CENTER>
<OBJECT CLASSID="clsid:D96FBCC1-090A-101C-BAC7-040224009C02" 
HEIGHT=80  WIDTH=100 ID=Ctrl1></OBJECT>
<INPUT TYPE = TEXT NAME = Textbox SIZE=20>
</CENTER>
<SCRIPT LANGUAGE = VBScript>
        Sub Page_Initialize
   -->          Ctrl1.Beep()
                Ctrl1.Counter = 5
        End Sub
</SCRIPT>
</BODY>
</HTML>

That's it—it was easy to add a new method and reach it from VBScript. The next step is to support custom events, and we'll take a look at that now.

© 1996 by Steven Holzner. All rights reserved.