[vb.net]判断窗体是否已打开

时间:2023-11-22 21:30:26

1.使用OpenForms

if my.Application.OpenForms.Item("FormName") isnot nothing then搜索
do something here
else
do something here
end if

2.使用FindWindow API

首先取得一个窗体的句柄(使用FindWindow[vb.net]判断窗体是否已打开),然后使用IsWindowVisible判断此窗体是否显示,还有一个IsIconic判断窗体是否已经最小化。

相关使用方法你简单查找一下就可以了,下面是三个函数的使用声明:

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function IsWindowVisible Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function IsIconic Lib "user32" Alias "IsIconic" (ByVal hwnd As Long) As Long
相关的使用示例:
Dim I As Long, J As Long, K As Long
I = FindWindow(vbNullString, "我的程序")
'I为0表示“我的程序”没有运行,否则它是程序的句柄
J = IsWindowVisible(I)
'J--如窗口可见则返回TRUE(非零)
K = IsIconic(I)
'判断窗口是否已最小化,非零表示成功,零表示失败

3.使用Process

        Dim myProcesses As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcessesByName("TrackRecorder")
If myProcesses.Length > Then
MessageBox.Show("TrackRecorder.exe has run.")
Windows.Forms.Application.Exit()
End If