Further down the spectrum of customization from owner-drawn controls are those controls that have exactly the UI you require but not the functionality you need. You can approach such situations by using a different technique: Identify a suitable existing control, derive from it, and add your desired functionality. For example, let's assume that you want to create a FileTextBox control that's just like the TextBox control except that it indicates to the user whether the currently entered file exists. Figures 10.12 and 10.13 show the FileTextBox control in use. Figure 10.12. FileTextBox with a File That Does Not Exist
Figure 10.13. FileTextBox with a File Name That Does Exist
By putting this functionality into a reusable control, you can drop it onto any form without making the form itself provide the functionality. By deriving FileTextBox from the TextBox base control class, you get most of the behavior you need without any effort, and thus you can focus on the interesting new functionality: class FileTextBox : TextBox { protected override void OnTextChanged(EventArgs e) { // Let the base class process changed text first base.OnTextChanged(e); // If the file does not exist, color the text red if( !File.Exists(this.Text) ) { this.ForeColor = Color.Red; } else { // Make it black this.ForeColor = Color.Black; } } } Notice that implementing FileTextBox is merely a matter of deriving from the TextBox base class (which provides all the editing capabilities that users expect) and overriding the OnTextChanged method (instead, you could handle the TextChanged event). When the text changes, we use the Exists method of the System.IO.File class to check whether the currently entered file exists in the file system; then, we set the foreground color of the control accordingly. Often, you can use as little code as this to easily create new controls that have application-specific functionality because the bulk of the code is provided by the base control class. |