Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to control other windows running outside excel

Status
Not open for further replies.

TingtingZhao

IS-IT--Management
Apr 5, 2007
2
US
Hi,

I am just wondering if there is a way to control other window outside excel by using VBA. What I am trying to achieve is to simulate the click action on the other outside programs. For example, if there is a force download dialog appeared, I like to get vba to simulate click action on that form. I think that this may be done by using win32 api function (like mouse_move, mouse_up). But I don't know how to call those win32 function in vba excel. Thank you for help in advance.
 
Search Google for Window Handles, FindWindow, FindWindowEx, SendMessage and PostMessage.
 
The following code will click buttons on Microsoft's Calculator program.

Code:
Option Explicit

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Private Const WM_LBUTTONDOWN = &H201
Private Const WM_LBUTTONUP = &H202

Private Sub CommandButton1_Click()
   Dim parent_handle As Long, child_handle As Long
   
   ' You'll need a window spy application to see the class name
   parent_handle = FindWindow("SciCalc", "Calculator")
   
   If parent_handle = 0 Then
      MsgBox "Calculator is not open..."
   Else
      ' Click the number 1 on the calculator
      child_handle = FindWindowEx(parent_handle, 0, "Button", "1")
      Call click_button(child_handle)
      
      ' Click the number 2 on the calculator
      child_handle = FindWindowEx(parent_handle, 0, "Button", "2")
      Call click_button(child_handle)
   
      ' Click the number 3 on the calculator
      child_handle = FindWindowEx(parent_handle, 0, "Button", "3")
      Call click_button(child_handle)
      
      ' Click Cancel on the calculator
      ' child_handle = FindWindowEx(parent_handle, 0, "Button", "C")
      ' Call click_button(child_handle)
   End If
End Sub

Private Sub click_button(child_handle As Long)
   Call PostMessage(child_handle, WM_LBUTTONDOWN, 0, 0)
   Call PostMessage(child_handle, WM_LBUTTONUP, 0, 0)
End Sub
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top