Opening a Window Using Its Name

RogerSchlueter-7899 1,326 Reputation points
2024-03-26T09:29:31.52+00:00

From my MainWindow I am trying to open another window knowing only its name. In my MainWindow ViewModel, I have:

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (lpClassName As String, lpWindowName As String) As Long
Private Declare Function ShowWindow Lib "user32" (HWND As Long, ncmdShow As Long) As Boolean

Private ReadOnly Property _OpenWindow As New RelayCommand(Of Object)(AddressOf DoOpenWindow)
Public ReadOnly Property OpenWindow As RelayCommand(Of Object)
	Get
		Return _OpenWindow
	End Get
End Property
Private Sub DoOpenWindow(obj As Object)
	Dim WinName As String = CStr(obj)
	Dim XhWnd As Long = FindWindow(WinName, WinName)
	Debug.WriteLine(XhWnd)
	Dim x As Boolean = ShowWindow(XhWnd, 5)
	Debug.WriteLine(x)
End Sub

For testing purposes the Class, Name and Title of the window to be opened are all set to "NewWindow". The first Debug statement returns 0 so the function FindWindow is not working. Where is the error?

Additional questions:

  1. Since this is a 64 bit application, is the use of 32 bit functions an issue?
  2. More broadly, is there a better way to do this? I have been unable to find one.
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,784 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,737 questions
{count} votes

Accepted answer
  1. KOZ6.0 6,500 Reputation points
    2024-03-28T03:32:20.06+00:00

    This is a sample of opening a window by specifying its class name.

    Imports System.Reflection
    
    Private Sub DoOpenWindow(className As String)
        For Each type In Assembly.GetExecutingAssembly().GetTypes()
            If type.IsSubclassOf(GetType(Window)) AndAlso type.Name = className Then
                Dim window = CType(Activator.CreateInstance(type), Window)
                window.Show()
                Exit For
            End If
        Next
    End Sub
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.