I want to detect if a window form is open and if it is then I would like to bring it in front rather than opening it again.
I know I need a form collection for this but I want to know if there is a built in form collection that holds all the forms in开发者_JS百科 VB.NET or I need to implement my own.
Thank you.
You could try:
'Pass the form object (you could also use string as the
'parameter and replace the if condition to: "If form.Name.Equals(targetForm) Then")
Public Sub BringToFront(ByVal targetForm As Form)
Dim form As Form
For Each form In Application.OpenForms()
If form Is targetForm Then
form.BringToFront()
Exit For
End If
Next
End Sub
Call this sub if you need to bring a specific form on front (only if it is already loaded) like this:
BringToFront(targetformobject)
Use the Application.OpenForms
property.
Using LINQ:
Dim existingForm = Application.OpenForms.OfType(Of YourFormType)().FirstOrDefault()
I've always P/Invoke code to call into the user32 windows dll. Something like this should do what you want.
<DllImport("user32.dll")> _
Public Shared SetFocus(ByVal hwnd As IntPtr)
Private Sub SetFocusToExistingWindow()
Dim procs As Process() = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName)
If procs.Length > 0 Then
Dim hwnd As IntPtr = procs(0).MainWindowHandle
SetFocus(hwnd)
End If
End Sub
精彩评论