Subclassing a Control

Like WinForm subclassing, control subclassing is much easier in VB.NET. In fact, to subclass a control, we can take the example application presented in the Section 22.2.2 section and change one line of code. To subclass a control, all you have to do is assign its Handle property value to a class that inherits from the NativeWindow class. This subclass will contain an overridden implementation of the WndProc method, which contains the actual subclassing code.

The application

The application presented in this section is exactly the same as the one presented in the Section 22.2.2 section. The only differences are that the window caption has changed to “VB.NET Control Subclassing Example,” and one line of code also has changed. I will discuss the code modification shortly. Figure 22-4 presents a screenshot of this application.

Subclassing a text box control

Figure 22-4. Subclassing a text box control

The .VB file

Example 22-5 presents the code for this technique. The modified code appears in boldface.

Example 22-5. The Form1.vb File Using the Control Subclassing Technique

Imports System.ComponentModel Imports System.Drawing Imports System.WinForms Public Class Form1 Inherits System.WinForms.Form Dim sc As New MySubClass( ) Public Sub New( ) MyBase.New( ) Form1 = Me InitializeComponent( ) sc.SetRefToTextBox(Me) End Sub 'Form overrides dispose to clean up the component list. Public Overrides Sub ...

Get Subclassing and Hooking with Visual Basic now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.