JMecham
JMecham

Reputation: 291

Is there a way to programmatically give focus to an application in windows?

I want to build an application using Visual Basic that will run in a Windows environment. The application should be very simple: Two buttons, and each of those buttons cause a different application to gain focus, pulling it forward in front of the Visual Basic app.

Can this be done?

If it can not be done with Visual Basic, is there another programming language for which it can be done where a simple UI is fairly easy to create?

Upvotes: 2

Views: 2336

Answers (1)

Lodewijk
Lodewijk

Reputation: 100

Something like this

01  ' Used to get access to Win API calling attributes
02  Imports System.Runtime.InteropServices
03   
04  Public Class Form1
05      ' This is 2 functions from user32.dll (1 for finding the application and 1 to set it to foreground with focus)
06      <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
07      Private Shared Function FindWindow( _
08       ByVal lpClassName As String, _
09       ByVal lpWindowName As String) As IntPtr
10      End Function
11   
12      <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
13      Private Shared Function SetForegroundWindow(ByVal hWnd As IntPtr) As Long
14      End Function
15   
16      ' Here we are looking for notepad by class name and caption
17      Dim lpszParentClass As String = "Notepad"
18      Dim lpszParentWindow As String = "Untitled - Notepad"
19   
20      Dim ParenthWnd As New IntPtr(0)
21   
22   
23      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
24          ' Find the window and get a pointer to it (IntPtr in VB.NET)
25          ParenthWnd = FindWindow(lpszParentClass, lpszParentWindow)
26   
27          If ParenthWnd.Equals(IntPtr.Zero) Then
28              Debug.WriteLine("Notepad Not Running!")
29          Else
30              ' Found it, so echo that we found it to debug window
31              ' Then set it to foreground
32              Debug.WriteLine("Notepad Window: " & ParenthWnd.ToString())
33              SetForegroundWindow(ParenthWnd)
34          End If
35      End Sub
36  End Class
enter code here

https://www.google.nl/search?client=opera&q=focus+program+VB

Do not use AppActivite which Google might also tell you about.

Upvotes: 2

Related Questions