Afshin Toussipour
Afshin Toussipour

Reputation: 11

How to run a process In VB .net and then run a click button in that process?

Can anyone help me to do this. I am trying to run a process and then activate a button in that process.

Something like this

I have a .exe file like WPF.exe which has a start button.

this is the code .. I know it is not working this way but what is the right way to do this?

    Process.run("WPF.exe")

    ' i have no idea how to run this start button 

    Start_Click(sender, New System.EventArgs())

    MsgBox("Start button clicked")

Upvotes: 0

Views: 1004

Answers (1)

Justin Ryan
Justin Ryan

Reputation: 1404

Events like button clicks are essentially just messages sent between processes behind the scenes in the operating system. Each 'process' (or window, control, etc..) has its own ID called a handle, each unique. You can use the Windows Message API to find the handle of the control you're looking for, and then send messages to it.

The first thing you need to do is declare the functions you will be using, and tell the compiler where to find them. You can also take this opportunity to declare the click message constant (it gets used later). That looks like this:

Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
Private Declare Function FindWindowEx Lib "user32.dll" Alias "FindWindowExA" (ByVal hwndParent As IntPtr, ByVal hwndChildAfter As IntPtr, ByVal lpszClass As String, ByVal lpszWindow As String) As IntPtr
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

Private Const BM_CLICK As Integer = &HF5

Then, in your code, you can call these functions to first, find the handle to the parent window (probably the window that contains the button you want to click), second, use that handle to find the handle of the button control you want to click, and finally, send a click message to that button.

Dim hWindow As IntPtr = FindWindow(vbNullString, "Window Title")
Dim hButton As IntPtr = FindWindowEx(hWindow, vbNullString, vbNullString, "Button Text")
Dim result As Integer = SendMessage(hButton, BM_CLICK, 0, 0)

Note that you may want to do some 'error checking' after each step to make sure you've properly captured the control handles (hWindow and hButton), and that you got a non-Null result back from SendMessage.

More Info:

To learn more about each of these API functions, you can have a look at their MSDN pages:

Upvotes: 3

Related Questions