用FindWindows函数查找
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Sub Form_Load()
Dim WinWnd As Long, Ret As String, RetVal As Long, lpClassName As String
'Ask for a Window title
Ret = InputBox("Enter the exact window title:" + Chr$(13) + Chr$(10) + "Note: must be an exact match")
'Search the window
WinWnd = FindWindow(vbNullString, Ret)
If WinWnd = 0 Then MsgBox "Couldn't find the window ...": Exit Sub
End Sub
Private Declare Function CreateFile Lib "KERNEL32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, lpSecurityAttributes As String, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
Private Declare Function CloseHandle Lib "KERNEL32" (ByVal hObject As Long) As Long
Private Const GENERIC_READ = &H80000000
Private Const GENERIC_WRITE = &H40000000
Private Const OPEN_EXISTING = 3
Private Const FILE_ATTRIBUTE_NORMAL = &H80
Private Const INVALID_HANDLE_VALUE = -1
Private Function IsFileRun(ByVal pFile As String) As Boolean
Dim ret As Long
ret = CreateFile(pFile, GENERIC_READ Or GENERIC_WRITE, 0&, vbNullString, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0&)
IsFileRun = (ret = INVALID_HANDLE_VALUE)
CloseHandle ret
End Function
用法:
if dir("c:/myfile.exe")<>"" and IsFileRun("c:/myfile.exe") then msgbox "文件c:/myfile.exe已运行!"
说明:由于这个函数在文件不存在的情况下也会返回true,所以要先用dir检查一下文件是否存在。