mdeforge
mdeforge

Reputation: 864

Show window of another program

I've created a GUI in Visual Basic 2010 that launches another program, except the other program is hidden behind the GUI window when it starts. I'm already retrieving the Process ID of that other program in order to later kill it, but I'm not sure how to turn the ID into something I can use to bring the window forward.

The other solution is to move send my GUI to the back, but that doesn't work either. I think that's because of the other program though. There's a splash screen that comes up before the main window launches that requires interaction. My program doesn't get sent to back until after the splash screen is closed, defeating the purpose.

Upvotes: 0

Views: 1252

Answers (2)

Joe Uhren
Joe Uhren

Reputation: 1372

There are a couple ways you could do this. You can use AppActivate as Timmy has suggested or you can use pinvoke with the SetForegroundWindow function:

Imports System.Runtime.InteropServices

Public Class Form1
    Dim oProcess As New Process()

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Add buttons to the form

        Dim cmd As New Button
        cmd.Name = "cmdAppActivate"
        cmd.Text = "App Activate"
        cmd.Location = New Point(0, 0)
        cmd.Size = New Size(90, 25)
        AddHandler cmd.Click, AddressOf cmdAppActivate_Click
        Me.Controls.Add(cmd)

        cmd = New Button
        cmd.Name = "cmdSetForegroundWindow"
        cmd.Text = "Set Foreground Window"
        cmd.Location = New Point(0, 30)
        cmd.Size = New Size(130, 25)
        AddHandler cmd.Click, AddressOf cmdSetForegroundWindow_Click
        Me.Controls.Add(cmd)

        ' Open notepad

        oProcess.StartInfo = New ProcessStartInfo("notepad.exe")
        oProcess.Start()
    End Sub

    Private Sub cmdAppActivate_Click(sender As Object, e As EventArgs)
        AppActivate(oProcess.Id)    ' use appactivate to bring the notepad window to the front
    End Sub

    Private Sub cmdSetForegroundWindow_Click(sender As Object, e As EventArgs)
        SetForegroundWindow(oProcess.MainWindowHandle)  ' Use pinvoke (SetForegroundWindow) to bring the notepad window to the front
    End Sub
End Class

Module Module1
    <DllImport("user32.dll")> _
    Public Function SetForegroundWindow(ByVal hWnd As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function
End Module

Upvotes: 1

Timmy
Timmy

Reputation: 553

Have you looked into AppActivate. It's supposed to set focus to the application you want as long as it's running.

Upvotes: 2

Related Questions