Microsoft KB Archive/137093

= How to Get a Control Reference from the Control's hWnd =

Article ID: 137093

Article Last Modified on 11/18/2003

-

APPLIES TO


 * Microsoft Visual Basic 4.0 Standard Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 Enterprise Edition

-



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
  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); }                        Start a new project in Visual Basic. Form1 is created by default. Add a command button (Command1) to Form1.  Add the following code to the General Declarations section of Form1: Dim x as control   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  Add a Module (Module1.Bas) to your project.  Add the following line to the General Declarations section of Module1: Declare Function GetTheHctl lib "mydll.dll" (byval hwnd%) As Control </li> Start the program by pressing the F5 key.</li> Click Form1. The program identifies and returns a reference to Command1 based on its hWnd. The output is:

Command1

</li></ol>

Additional query words: 4.00 vb4win vb416

Keywords: kbcode KB137093

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.