Wait for UI to load new window before continuing - vb.net

I am novice of VB.Net trying to create a plugin for a program with a fairly lacking API. Essentially what I am trying to accomplish is press a button in the interface, which will create a new window. Once this window loads, I have a couple other buttons to press to eventually print out an HTML file it generates.
I attempted to use Windows UI Automation, but was unable to manipulate the first control (it appeared as a "pane" element for some reason, and had no supported control patterns)
I eventually was able to use PostMessage to send a MouseDown and MouseUp message to the control to activate it.
My question is: What is the best way for me to wait for this window to finish loading before continuing my code execution?
I tried using Thread.Sleep after I sent the click to my control, but my code seemed to trigger the sleep before it even started to load the window. I suspect there may be some kind of event-driven options, but I don't even know where I would begin with that.
Side note: I do have access to the program's Process ID if that helps.
EDIT:
To be more explicit about what I have done, here is some code for you to look at:
' These variables declared further up in my program, when plugin is loaded
Private aeDesktop As AutomationElement
Private aeRadan As AutomationElement
Private aeBlocksBtn As AutomationElement
Private Sub UITest1()
Dim rpid As Integer
Dim intret As Integer
' Note: mApp is declared further up in the code, when the plug in initializes
' It sets a reference to the application object (API command from the software)
rpid = mApp.ProcessID
aeDesktop = AutomationElement.RootElement
Dim propcon As New PropertyCondition(AutomationElement.ProcessIdProperty, rpid)
Dim propcon2 As New PropertyCondition(AutomationElement.NameProperty, "big_button_blocks.bmp")
aeRadan = aeDesktop.FindFirst(TreeScope.Children, propcon)
aeBlocksBtn = aeRadan.FindFirst(TreeScope.Descendants, propcon2)
' MAKELONG is a function that concatenates given x and y coordinates into an appropriate "lparam" value for PostMessage.
' Coordinates 20, 20 are chosen arbitrarily
Dim lParam As Long = MAKELONG(20, 20)
intret = PostMessage(CInt(aeBlocksBtn.GetCurrentPropertyValue(AutomationElement.NativeWindowHandleProperty)), &H201, &H1, lParam)
intret = PostMessage(CInt(aeBlocksBtn.GetCurrentPropertyValue(AutomationElement.NativeWindowHandleProperty)), &H202, &H0, lParam)
Dim bwinprop As New PropertyCondition(AutomationElement.NameProperty, "Radan Block Editor")
Dim aeblockwin As AutomationElement
Dim numwaits As Integer = 0
Do
numwaits += 1
Thread.Sleep(100)
aeblockwin = aeRadan.FindFirst(TreeScope.Children, bwinprop)
Loop While (numwaits < 50) AndAlso (aeblockwin Is Nothing)
If numwaits >= 50 Then
MessageBox.Show("ERROR: Block Editor Window Not found")
End If
I am fairly sure what is happening has to do with the code moving to the Do While loop before the PostMessage is processed by the program. I have tried using SendMessage to try to bypass this, but unfortunately that does not seem to work.
I feel like there is a pretty simple solution here, like maybe some kind of alternate wait or sleep command that I don't know about, so maybe someone could help guide me to it?
EDIT 2:
Screenshot of the inspect.exe output for this control.
Also, a screenshot of the user interface. This is from Radan, a CAM software I use for nesting and processing sheet metal parts to be laser cut. I put a red box around the control I would like to activate.

Related

Using VB .net to click command button in Access

I'm trying to click a button in a form in MS Access with VB .net. However, there isn't much I can find in this area and have a bit of a long way of getting the button. Then I'm stuck - there seems to be no way to activate the click event.
Using :
Imports Microsoft.Office.Interop
I have the following to get the button:
Dim acc As New Access.Application
acc.OpenCurrentDatabase("C:\path\to\db\aDatabase.accdb")
acc.Visible = True
For i = 0 To acc.Forms.Count - 1
If acc.Forms.Item(i).Name = "formName" Then
For j = 0 To acc.Forms.Item(i).Controls.Count - 1
If acc.Forms.Item(i).Controls.Item(j).name = "btnEnter" Then
Dim btn As Access.CommandButton = acc.Forms.Item(i).Controls.Item(j)
'
' click on button??
'
End If
Next
End If
Next
I've had a guess at trying the following:
acc.Application.Run(btn.OnClickMacro)
acc.Application.Run(btn.OnClick)
btn.OnClickMacro
btn.OnClick
btn.performclick()
none of which work.
By default, the click event handler is declared in VBA as
Private Sub Command0_Click()
' do something
End Sub
You won't be able to programmatically click the button outside of Access' VBA code if it's private (unless the developer intentionally declared it public). Best practice is to make a function which is called by the handler, which can be called elsewhere as well, instead of clicking buttons through code.
Private Sub Command0_Click()
DoSomething
End Sub
' you would have a better chance calling this from .NET
Public Sub DoSomething()
' do something
End Sub
If you don't have access to the Access VBA code, outside of .NET you could use something to automate mouse clicks like this: https://autohotkey.com/
I mean, if you have to have Access intslled, open and running, then why is such code not being run from Access? So it does not make a whole lot of sense to call such code from .net.
However, simply make the private sub click as public, and then you can use this form:
MyAccessApp.Forms("main").command44_click
So you don’t have to create any external functions etc., but if you wish to call that code directly then the form MUST be opened, and with a running instance of that application from .net, then the above syntax will work.
I would suggest you just use Access here, and it nots clear why .net is involved.

Adding nodes to treeview with Begin Invoke / Invoke

I've been working through my first project and have had a great deal a valuable help from the guys on SO but now I'm stuck again.
The below sub is used to add TreeNodes to a TreeView, excluding certain filetypes/names, upon addition of new data:
Sub DirSearch(ByVal strDir As String, ByVal strPattern As String, ByVal tvParent As TreeNodeCollection)
Dim f As String
Dim e As String
Dim tvNode As TreeNode
Dim ext() As String = strPattern.Split("|"c)
Try
For Each d In Directory.GetDirectories(strDir)
If (UCase(IO.Path.GetFileName(d)) <> "BACKUP") And (UCase(IO.Path.GetFileName(d)) <> "BARS") Then
tvNode = tvParent.Add(IO.Path.GetFileName(d))
For Each e In ext
For Each f In Directory.GetFiles(d, e)
If (UCase(IO.Path.GetFileName(f)) <> "DATA.XLS") And (UCase(IO.Path.GetFileName(f)) <> "SPIRIT.XLSX") Then
tvNode.Nodes.Add(IO.Path.GetFileName(f))
End If
Next
Next
DirSearch(d, strPattern, tvNode.Nodes)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I'm now getting an error:
Action being performed on this control is being called from the wrong thread. Marshal to the correct thread using Control.Invoke or Control.BeginInvoke to perform this action.
On the following line:
tvNode = tvParent.Add(IO.Path.GetFileName(d))
Obviously, I understand its to do with 'threading' and the use of BeginInvoke / Invoke but even after reading the MSDN documentation on the error, I have no idea where to start.
This error only occurs, if I add a file to the initial directory (which is also the subject of a File System Watcher to monitor new additions).
Would someone be so kind as to give me an explanation in layman's terms so I may be able to understand.
This code is being run on a background thread where it's illegal to modify UI elements. The Invoke / BeginInvoke methods are ways to schedule a piece of code to run on UI thread where elements can be modified. For example you could change your code to the following
Dim action As Action = Sub() tvNode.Nodes.Add(IO.Path.GetFileName(f))
tvNode.TreeView.Invoke(action)
This code will take the delegate instance named action and run it on the UI thread where edits to tvNode are allowed
Fixing the earlier Add call is a bit trickier because there is no Control instance on which we can call BeginInvoke. The signature of the method will need to be updated to take a Dim control as Control as a parameter. You can pass in the TreeView for that parameter if you like. Once that is present the first Add can be changed as such
Dim outerAction As Action = Sub() tvNode = tvParent.Add(IO.Path.GetFileName(d))
control.Invoke(outerAction)

Detect when exe is started vb.net

Dose anybody know how I can make my VB.net application wait until a process is detected as running?
I can find example of how to detect once an exe has finished running but none that detect when an exe is started?
You can use the System.Management.ManagementEventWatcher to wait for certain WMI events to occur. You need to give it a query type and condition to have it watch for the next creation of your process, then get it to do something when that occurs.
For example, if you want :
Dim watcher As ManagementEventWatcher
Public Sub Main()
Dim monitoredProcess = "Notepad.exe"
Dim query As WqlEventQuery = New WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa ""Win32_Process"" And TargetInstance.Name = """ & monitoredProcess & """")
watcher = New ManagementEventWatcher()
watcher.Query = query
'This starts watching asynchronously, triggering EventArrived events every time a new event comes in.
'You can do synchronous watching via the WaitForNextEvent() method
watcher.Start()
End Sub
Private Sub Watcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles watcher.EventArrived
'Do stuff with the startup event
End Sub
Eventually you'll need to stop the watcher, which is you can do by closing the app, or calling watcher.Stop(). This has been written as brain compiler, so if there's any issues let me know.
You could simply wait and check every once in a while whether the process exists. Use Thread.Sleep to avoid busy waiting.
However, this has the possibility that you miss the process if it starts and exists during your wait time.
You can use the below condition
return Process.GetProcesses().Any(Function(p) p.Name.Contains(myProcessName))
Dim p() As Process
Private Sub CheckIfRunning()
p = Process.GetProcessesByName("processName")
If p.Count > 0 Then
' Process is running
Else
' Process is not running
End If
End Sub
OR SIMPLY
System.Diagnostics.Process.GetProcessesByName("processName")

Accessing Form1 Properties From Thread

I have an exceptionhandler function that basically just writes a line to a textbox on Form1. This works fine when being run normally but the second I use a thread to start a process it cannot access the property. No exception is thrown but no text is written to the textbox:
Public Sub ExceptionHandler(ByVal Description As String, Optional ByVal Message As String = Nothing)
' Add Error To Textbox
If Message = Nothing Then
Form1.txtErrLog.Text += Description & vbCrLf
Log_Error(Description)
Else
Form1.txtErrLog.Text += Description & " - " & Message & vbCrLf
Log_Error(Description, Message)
End If
MessageBox.Show("caught")
End Sub
Is it possible to access a form's properties from a thread this way or would it be easier to write to a text file or similar and refresh the textbox properties every 10 seconds or so (Don't see this as a good option but if it's the only way it will have to do!).
Also, still new to VB so if I have done anything that isn't good practice please let me know!
No, you shouldn't access any GUI component properties from the "wrong" thread (i.e. any thread other than the one running that component's event pump). You can use Control.Invoke/BeginInvoke to execute a delegate on the right thread though.
There are lots of tutorials around this on the web - many will be written with examples in C#, but the underlying information is language-agnostic. See Joe Albahari's threading tutorial for example.
You have to use delegates. Search for delegates in VB.
Here a peace of code that does the job.
Delegate Sub SetTextCallback(ByVal text As String)
Public Sub display_message(ByVal tx As String)
'prüfen ob invoke nötig ist
If Me.RichTextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf display_message)
Me.Invoke(d, tx)
Else
tx.Trim()
Me.RichTextBox1.Text = tx
End If
End Sub

Simplest way to send messages between Matlab, VB6 and VB.NET programs

We are upgrading a suite of data acquisition and analysis routines from VB6 programs to a mixture of VB.NET, VB6, and Matlab programs. We want to keep the system modular (separate EXEs) so we can easily create specialized stand-alone analysis programs without having to constantly upgrade one massive application. We have used MBInterProcess to send messages between EXEs when all the programs were written in VB6 and this worked perfectly for us (e.g., to have the data acquisition EXE send the latest file name to a stand-alone data display program). Unfortunately, this ActiveX cannot be used within Matlab or VB.NET to receive messages. We are wondering what is the simplest string message passing system (pipes, registered messages, etc) that we could adopt. Right now we are just polling to see if new file was written in a specific folder, which can't be the best solution. Our ideal solution would not require a huge investment in time learning nuances of Windows (we are biologists, not full-time programmers) and would work in both WinXP and 64-bit versions of Windows.
In response to the queries, we have wrapped the entire Matlab session within a VB6 program that has the MBInterProcess ActiveX control. That works but is not a great solution for us since it will probably lock us into WinXP forever (and certainly will prevent us from using the 64-bit version of Matlab). The latest version of Matlab (2009a) can access .NET functions directly, so we assume one solution might be to use the .NET library to implement pipes (or something similar) across programs. We would like to recreate the elegantly simple syntax of the MBInterProcess ActiveX and have a piece of code that listens for a message with that program's top-level Windows name, and then call a specific Matlab m-file, or VB.NET function, with the string data (e.g., file name) as an argument.
Could you create an ActiveX EXE in VB6 to simply forward messages between the different parties? When anyone called it, it would raise an event with the parameters passed to the call. Your VB6 and VB.NET code could establish a reference to the ActiveX exe to call it and sink its events. I'm not familiar with Matlab so I don't know whether it would be accessible there.
EDIT: you've written that Matlab 2009a can access .NET directly. If it can sink .NET events, you could also have a .NET wrapper on the VB6 ActiveX EXE.
Here's some sample code I knocked up quickly.
VB6 ActiveX EXE project with project name VB6MatlabMessenger. Each message has a text string Destination (that somehow identifies the intended recipient) and a string with the message.
'MultiUse class VB6Messenger
Option Explicit
Public Event MessageReceived(ByVal Destination As String, ByVal Message As String)
Public Sub SendMessage(ByVal Destination As String, ByVal Message As String)
Call Manager.RaiseEvents(Destination, Message)
End Sub
Private Sub Class_Initialize()
Call Manager.AddMessenger(Me)
End Sub
Friend Sub RaiseTheEvent(ByVal Destination As String, ByVal Message As String)
RaiseEvent MessageReceived(Destination, Message)
End Sub
'BAS module called Manager
Option Explicit
Private colMessengers As New Collection
Sub AddMessenger(obj As VB6Messenger)
colMessengers.Add obj
End Sub
Sub RaiseEvents(ByVal Destination As String, ByVal Message As String)
Dim obj As VB6Messenger
For Each obj In colMessengers
Call obj.RaiseTheEvent(Destination, Message)
Next obj
End Sub
And a test VB6 normal exe, with a reference to the VB6MatlabMessenger. Here is the whole frm file. Build this as an exe, run a few copies. Fill in the destination and message text fields and click the button - you will see that the messages are received in all the exes (reported in the listboxes).
VERSION 5.00
Begin VB.Form Form1
Caption = "Form1"
ClientHeight = 3090
ClientLeft = 60
ClientTop = 450
ClientWidth = 4680
LinkTopic = "Form1"
ScaleHeight = 3090
ScaleWidth = 4680
StartUpPosition = 3 'Windows Default
Begin VB.ListBox lstEvents
Height = 1620
Left = 120
TabIndex = 3
Top = 1320
Width = 4455
End
Begin VB.TextBox txtMessage
Height = 375
Left = 120
TabIndex = 2
Text = "Message"
Top = 840
Width = 2295
End
Begin VB.TextBox txtDestination
Height = 375
Left = 120
TabIndex = 1
Text = "Destination"
Top = 240
Width = 2295
End
Begin VB.CommandButton cmdSendMessage
Caption = "Send Message"
Height = 495
Left = 2640
TabIndex = 0
Top = 360
Width = 1575
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private WithEvents objMessenger As VB6MatlabMessenger.VB6Messenger
Private Sub cmdSendMessage_Click()
objMessenger.SendMessage txtDestination, txtMessage.Text
End Sub
Private Sub Form_Load()
Set objMessenger = New VB6MatlabMessenger.VB6Messenger
End Sub
Private Sub objMessenger_MessageReceived(ByVal Destination As String, ByVal Message As String)
lstEvents.AddItem Now() & " RECEIVED - " & Destination & ", " & Message
End Sub
I started writing a VB.NET class library that wraps the VB6 to make it accessible to .NET. I haven't tested this one. It has a reference to the VB6MatLabMessenger.
Public Class VBNETMatlabMessenger
Private WithEvents objVB6Messenger As VB6MatlabMessenger.VB6Messenger
Public Event MessageReceived(ByVal Destination As String, ByVal Message As String)
Public Sub SendMessage(ByVal Destination As String, ByVal Message As String)
objVB6Messenger.SendMessage(Destination, Message)
End Sub
Public Sub New()
objVB6Messenger = New VB6MatlabMessenger.VB6Messenger
End Sub
Private Sub objVB6Messenger_MessageReceived(ByVal Destination As String, ByVal Message As String) Handles objVB6Messenger.MessageReceived
RaiseEvent MessageReceived(Destination, Message)
End Sub
End Class
This might get you started. Note that the VB6 messenger objects will live forever because the messenger keeps a reference to them internally, so COM will never tidy them up. If this becomes a problem (if many messages are sent without rebooting the PC) you could add a method to the VB6 messenger which instructs it to removed the messenger object from its collection,
I've used the Matlab dos command to execute a Java program on the commandline, it waits for the commandline to complete before returning control to Matlab. This worked fine for me, after my Matlab program regained control I read the output file from the Java.
I've used compiled Matlab programs (i.e. exe's), these work okay but they spray files around when they execute - I believe it's possible to pass in commandline arguments to a compiled executable. Assuming VB.NET is like C# .NET you could execute your exe from code using something like the Process object.
Alternatively there are ways to compile to .dll which are accessible via .NET see here:
http://www.codeproject.com/KB/dotnet/matlabeng.aspx
for an explanation. I've never tried this...