Microsoft KB Archive/137093

From BetaArchive Wiki
Knowledge Base


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

  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



Additional query words: 4.00 vb4win vb416

Keywords: kbcode KB137093