148
❘
CHAPTER 8
Creating WindoWs Forms appliCations
# Always add event handlers after defining the Windows Form.
TestForm.btnOK.Click += btnOK_Click
TestForm.btnCancel.Click += btnCancel_Click
Notice that you must drill down into the form in order to access the controls. Consequently, you
must provide the full path to the event, such as
TestForm.btnOK.Click
. IronPython lets you use
the
+=
operator to add an event handler to the
Click
event. If you want to remove the event handler,
all you need to use is the
–=
operator instead. Assigning the event handler is as easy as providing the
method name as shown in the code.
IronPython events can have more than one handler, as you’ll see in the section “Developing Your
Own Events.” As with any OOP language, you simply keep adding event handlers with the correct
signature (a combination of the right return type and input arguments). Unlike most OOP languages,
IronPython tends to make things very simple and you could actually find this approach detrimental
because there are times where the interpreter will output odd messages instead of telling you that the
event handler won’t work for the event to which you assigned it.
Performing Some useful Work as the Result of user Input
The Windows Forms application now has a form object and methods assigned to some of the events.
Of course, this means you need to provide the event handlers required to do the work. Event handlers
can come in a number of forms. When working with Windows Forms controls, you may never even
need the arguments that IronPython passes. The following code shows the event handlers used for
this example.
# Define the event handlers.
def btnOK_Click(*args):
# Display a message showing we arrived.
System.Windows.Forms.MessageBox.Show(‘Hello!’)
def btnCancel_Click(*args):
# Close the application.
TestForm.Close()
The code is a standard IronPython function. However, notice that the arguments have an asterisk
(*) in front of them. Essentially, this means that all the arguments passed to the event handler end
up in a sequence. In this case, that means you’ll end up with a list of event arguments. For a button
handler, you obtain two arguments:
➤
Sender
➤
Mouse arguments
➤
➤
Let’s say for a minute that the user has clicked OK. Then the sender argument would contain
System.Windows.Forms.Button, Text: &OK
548592c08.indd 148
2/24/10 12:48:10 PM
www.finebook.ir
Do'stlaringiz bilan baham: |