Simulating User Actions

Buttons being clicked

To simulate a user clicking a button, the code you need is more advanced... First, you need to get the hWnd of the button using the FindWindowEx API call. And to do this, you need to know its caption, and class name (always Button). For example, the following code finds a button with a caption "OK" within frmMain. If you don't know the hWnd of the form it is in, you need to find that as well!

lObjhWnd = FindWindowEx(frmMain.hWnd, 0, "Button", "OK")

Don't forget that many buttons will have 'access' keys so that you can click them using the keyboard. For example, if a button has a line under the letter C in its caption, you can click it by pressing Alt+t. So, if its caption appears to be "Cancel", but there is a line under the C, its caption is actually "&Caption" (just like in VB).

SendMessage lObjhWnd, BM_CLICK, 0, 0

Sometimes, you will find that the button must not have the focus before receiving the BM_CLICK message... you will just have to try and see. If this is the case, you can use the SetFocus API to set the focus to another item on the form:

SetFocus lOtherItemhWnd

The declarations you need for all this code are below.

Private Const BM_CLICK = &HF5
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 SetFocus Lib "user32" (ByVal hwnd As Long) As Long

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” - Brian Kernighan