Handling Keyboard Events

Building from the success thus far, I m going to extend the XMLNotepad class to have a keyboard handler. As soon as I get the handler to fire and let me put something into the text, I ll consider this spike done and start working test first. [3] After this one little spike to learn about the keyboard, I think I ll be at a good point to stop and rest. Here goes...

Well, Petzold seemed to be suggesting that I could override OnKeyDown, but I couldn t make that work. What did work, after some more reading, is to set up a handler. The program now looks like this:

 using System; 
using System.Drawing;
using System.Windows.Forms;

namespace Notepad1
class XMLNotepad : NotepadCloneNoMenu
static void Main(string[] args)
Application.Run(new XMLNotepad());

public XMLNotepad() {
Text = "XML Notepad";
txtbox.KeyDown += new KeyEventHandler(XMLKeyDownHandler);
void XMLKeyDownHandler(object objSender, KeyEventArgs kea) { if (kea.KeyCode == Keys.P && kea.Modifiers == Keys.Control) { txtbox.Text += "controlP";
kea.Handled = true;

This goofy little program just does one new thing. It works just like our previous notepad examples, unless you type Ctrl+P. In that case, the string controlP is appended to the textbox. Not very impressive, is it? And yet, this little spike embodies the essence of how the XML Notepad will work for most of this section of the book. You ll see that the Key Down handler will survive for a long time, providing more and more functionality to the program. So this trivial example has forged a link between the almost complete ignorance in which we started this chapter and a living, breathing program.

That s the essence of the spike concept. We try to hammer through our ignorance, not by building a complex, well-crafted program for the ages, but by finding something simple, ideally trivial, that bridges gaps in our knowledge. As we ll see, the experiments above told us enough to give our customer (that s us) some good information about what we can do now, and what we cannot as yet do.

[3] Test-first programming, or test-driven development, is the phrase we use for a style of program ming where we write new code only in response to a test we have written that does not work. Much of the work in this book will use that technique. Often, when doing a spike, I do not use test-driven style. You can help me decide, as we go forward, whether I should.

Extreme Programming Adventures in C#
Javaв„ў EE 5 Tutorial, The (3rd Edition)
ISBN: 735619492
EAN: 2147483647
Year: 2006
Pages: 291

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net