Mykal73
Mykal73

Reputation: 488

Microsoft word opening in the background

I have an application written in VB.net running on Windows 7 that opens a word document and inserts some values into it. This works fine, but on my client's machines(development works fine) Word is opening up behind my application. I've tried maximizing the document in code, but it's still opening behind my application on the client machines. Does anyone have any idea how I can fix this?

Things I've already tried:

Upvotes: 1

Views: 1847

Answers (2)

Don Nickel
Don Nickel

Reputation: 154

You might need to bring Word to the forefront. This is a bit different from bringing a form in your app to the top.

You'll need to have a reference to two APIs, FindWindow and SetWindowPos - the first one can find the windows handle for another application that is running, and the second sends a message to the operating system to give an application focus (it uses the windows handle from FindWindow)

Here's some sample code.

Public Class Form1

    <Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True, CharSet:=Runtime.InteropServices.CharSet.Auto)> _
    Private Shared Function FindWindow(ByVal lpClassName As String, _
                                       ByVal lpWindowName As String) As IntPtr
    End Function

    <Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function SetWindowPos(ByVal hWnd As IntPtr, ByVal hWndInsertAfter As IntPtr, ByVal X As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal uFlags As Integer) As Boolean
    End Function

    Private Shared ReadOnly HWND_TOPMOST As New IntPtr(-1)
    Private Shared ReadOnly HWND_NOTOPMOST As New IntPtr(-2)

    Private Const SWP_NOSIZE As Integer = &H1
    Private Const SWP_NOMOVE As Integer = &H2

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Shell("calc.exe")
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Dim myHandle As IntPtr = FindWindow(Nothing, "Calculator")

        SetWindowPos(myHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE)
        SetWindowPos(myHandle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE)

    End Sub

End Class

Clicking the first button will instantiate a copy of Calculator, the second button will make it topmost, then set it back to normal... so it will still be the top form, but the user can activate other windows as well.

Upvotes: 0

Dave H
Dave H

Reputation: 653

Have you tried minimizing the application, as opposed to maximizing the document?

Me.WindowState = FormWindowState.Minimized will minimize the form that calls it (this is assuming that you are using a forms application).

Upvotes: 1

Related Questions