Tác giả: truongphu
Mô tả: Tìm hWnd của Process. (Chẳng biết bài tương tự có chưa? nhưng thấy có câu hỏi "Lấy tiêu đề các process đang hoạt động" ...)
* Phần VBS tìm Process ID
* Phần VB6 tìm hWnd
Mã: Chọn hết
- Option Explicit
-
- Public strCache As String
- Private Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
- Private Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long
- Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
- Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwprocessid As Long) As Long
- Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
- (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
- Const WM_GETTEXTLENGTH = &HE: Const WM_GETTEXT = &HD: Const GW_HWNDNEXT = 2
-
- Private Sub Command1_Click()
- GetIPProcess
- End Sub
-
- Private Sub GetIPProcess() ' VBScript tìm Process ID
- Dim objProcess, objProcesses
- Set objProcesses = GetObject("winmgmts://").execquery("Select * from win32_process")
- ' truongphu, camlâm, khanhhoa
- For Each objProcess In objProcesses
- If UCase(objProcess.Name) = Text1.Text Then strCache = objProcess.Handle
- Next
-
- If strCache = "" Then
- MsgBox "Không Tìm Thâ'y."
- Else
- FindhWnd
- End If
-
- End Sub
-
- Private Sub FindhWnd()
- Dim hProcess As Long, hWndApp As Long
- hProcess = CLng(strCache)
- hWndApp = GetWinHandle(hProcess)
- If hWndApp <> 0 Then MsgBox "hWnd là: " & hWndApp & " Tiêu Ðê' là: " & WinGetText(hWndApp)
- End Sub
-
- Function ProcIDFromWnd(ByVal hwnd As Long) As Long
- Dim idProc As Long
- GetWindowThreadProcessId hwnd, idProc
- ProcIDFromWnd = idProc
- End Function
-
- Function GetWinHandle(hProcess As Long) As Long
- Dim tempHwnd As Long
- tempHwnd = FindWindow(vbNullString, vbNullString)
-
- Do Until tempHwnd = 0
- If GetParent(tempHwnd) = 0 And (hProcess = ProcIDFromWnd(tempHwnd)) Then
- GetWinHandle = tempHwnd
- Exit Do
- End If
- tempHwnd = GetWindow(tempHwnd, GW_HWNDNEXT)
- Loop
- End Function
-
- Function WinGetText(hwnd As Long) As String
- On Error Resume Next
- Dim length&, result&, strtmp$, S As Variant
- length& = SendMessage(hwnd, WM_GETTEXTLENGTH, ByVal 0, ByVal 0) + 1
- strtmp$ = Space$(length)
- result& = SendMessage(hwnd, WM_GETTEXT, ByVal length, ByVal strtmp)
- S = Split(strtmp, vbNullChar)
- WinGetText$ = S(0)
- End Function
-
- Private Sub Form_Load()
- Text1.Text = "NOTEPAD.EXE"
- Shell "Notepad"
- End Sub
-