Eric Christoph
Eric Christoph

Reputation: 346

VB.NET MS Project how to bring a form in front of the application?

I have a form as part of a VSTO Project application. For various reasons it can end up behind the main Project application window. How do I bring it back to the front? I've tried form.activate and form.bringtofront, but neither of those commands do anything.

Upvotes: 0

Views: 218

Answers (2)

Rachel Hettinger
Rachel Hettinger

Reputation: 8442

Here is code that I use to show/re-show forms in vb.net MS Project add-ins. If the form gets behind another window, calling ShowTkForm will bring it back to the front:

Friend formTk As tk
Friend Sub ShowTkForm()
    If formTk Is Nothing OrElse formTk.IsDisposed Then
        formTk = New tk
    End If
    formTk.Show()
End Sub

Note: for modeless forms, use the .Show method, otherwise use .ShowDialog.

For modeless forms, I also like to set the owner of the form as the MS Project application to keep them together. In the Load event of the form:

    Dim ip As IntPtr = FindWindowByCaption(0, ProjApp.Caption)
    SetWindowLong(New HandleRef(Me, Me.Handle), GWL_HWNDPARENT, New HandleRef(Nothing, ip))

Which requires:

Friend Const GWL_HWNDPARENT = (-8)
<DllImport("user32.dll", EntryPoint:="SetWindowLong", CharSet:=CharSet.Auto)>
Private Function SetWindowLongPtr32(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As HandleRef) As IntPtr
End Function
<DllImport("user32.dll", EntryPoint:="SetWindowLongPtr", CharSet:=CharSet.Auto)>
Private Function SetWindowLongPtr64(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As HandleRef) As IntPtr
End Function
Friend Function SetWindowLong(ByVal hWnd As HandleRef, ByVal nIndex As Integer, ByVal dwNewLong As HandleRef) As IntPtr
    If (IntPtr.Size = 4) Then
        Return SetWindowLongPtr32(hWnd, nIndex, dwNewLong)
    End If
    Return SetWindowLongPtr64(hWnd, nIndex, dwNewLong)
End Function

<DllImport("user32.dll", EntryPoint:="FindWindow", SetLastError:=True, CharSet:=CharSet.Auto)>
Friend Function FindWindowByCaption(ByVal zero As IntPtr, ByVal lpWindowName As String) As IntPtr
End Function

Upvotes: 1

Jerred S.
Jerred S.

Reputation: 376

It sounds like you want your form to be modal. I'm not sure what form library you're using, but if this were a MS Project VBA form, then you'd set the form's .ShowModal property to True: https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/showmodal-property.

Presuming you're using a .NET form, this may be more appropiate: https://msdn.microsoft.com/en-us/library/c7ykbedk(v=vs.110).aspx

Upvotes: 0

Related Questions