How to Get a Control Reference from the Control's hWnd (137093)



The information in this article applies to:

  • Microsoft Visual Basic Standard Edition for Windows 4.0
  • Microsoft Visual Basic Professional Edition for Windows 4.0
  • Microsoft Visual Basic Enterprise Edition for Windows 4.0

This article was previously published under Q137093

SUMMARY

Visual Basic exports a new function in the Visual Basic run time that can be used to return a control reference when all you have is the hWnd to the control. This article shows you how.

MORE INFORMATION

Microsoft Windows uses window handles to keep track of all windowed controls created. Visual Basic wraps this functionality with the hWnd property that all windowed controls have. Ordinarily it is quite difficult to trace backwards from the hWnd property to a reference to the control it represents. It would be necessary to walk through all the child windows of a task recursively and compare each window's hWnd to the one you are seeking. However, the VBGetHwndControl function allows you to do it in one simple call. This function is not available from within Visual Basic, but you can easily wrap it in a C-language DLL.

Step-by-Step Procedure

  1. Create a DLL in the language of your choice. The following code would be used for the C programming language. Enter the code, and compile it into a DLL called Mydll.dll.
       HCTL FAR PASCAL _export GetTheHctl(HWND hwnd)
          {
             return VBGetHwndControl(hwnd);
          }
    						
  2. Start a new project in Visual Basic. Form1 is created by default.
  3. Add a command button (Command1) to Form1.
  4. Add the following code to the General Declarations section of Form1:
       Dim x as control
    						
  5. Add the following code to the Form_Click event procedure for Form1:
       Sub Form_Click ()
          Set X = GetTheHctl(Command1.hwnd)
          MsgBox X.Caption
       End Sub
    						
  6. Add a Module (Module1.Bas) to your project.
  7. Add the following line to the General Declarations section of Module1:
       Declare Function GetTheHctl lib "mydll.dll" (byval hwnd%) As Control
    						
  8. Start the program by pressing the F5 key.
  9. Click Form1. The program identifies and returns a reference to Command1 based on its hWnd. The output is:

    Command1


Modification Type:MajorLast Reviewed:11/18/2003
Keywords:kbcode KB137093