หลักการทำงานของโปรแกรม คือการค้นหา Window Title ของโปรแกรม โดยใช้ API
FindWindow(Class,Title) หลังจากได้ค่า Handle จากการ FindWindow มาแล้วก็ใช้ API
GetWindowThreadProcessId( hWnd, lpdwProcessId)
มาทำการเปลี่ยน Window Handle ที่ค้นเจอ ให้เป็น Process Id Function GetWindowThreadProcessId
จะ Return ค่ามาเป็น DWORD หรือ ใน VB6 คือค่า Long
และหลังจากได้ค่า Process Id มาแล้วก็จะใช้ API GetModuleFileNameEx มาทำการค้นหาที่อยู่ของ
โปรแกรมที่ทำงาน
โค้ดตัวอย่าง
module1.bas
Public Const PROCESS_QUERY_INFORMATION As Long = (&H400)
Public Const PROCESS_VM_READ As Long = (&H10)
Public Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Public Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Public Declare Function EnumProcesses Lib "psapi.dll" (ByRef lpidProcess As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long
Public Declare Function EnumProcessModules Lib "psapi.dll" (ByVal hProcess As Long, ByRef lphModule As Long, ByVal cb As Long, ByRef lpcbNeeded As Long) As Long
Public Declare Function GetModuleFileNameEx Lib "psapi.dll" Alias "GetModuleFileNameExA" (ByVal hProcess As Long, ByVal hModule As Long, ByVal lpFilename As String, ByVal nSize As Long) As Long
Public Function PrintProc(ProcessID As Long) As String
Dim hProc As Long, hMod As Long, cbNeeded As Long
Dim strBuff As String, lRet As Long
strBuff = Space(260)
hProc = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, ProcessID)
If hProc <> 0 Then
If EnumProcessModules(hProc, hMod, 4&, cbNeeded) Then
lRet = GetModuleFileNameEx(hProc, hMod, strBuff, 260)
strBuff = Left$(strBuff, lRet)
PrintProc = strBuff
End If
CloseHandle hProc
End If
End Function
form1.frm
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
Function WindowToProcessId(ByVal hWnd As Long) As Long'Function เปลียน Window Handle เป็น PID
Dim lpProc As Long
Call GetWindowThreadProcessId(hWnd, lpProc)
WindowToProcessId = lpProc
End Function
Private Sub Timer1_Timer()
Dim hw As Long
hw = FindWindow(vbNullString, "ชื่อหน้าต่าง") 'Windows Title
If hw <> 0 Then
Text1.Text = WindowToProcessId(hw)
Timer1.Enabled = False
Timer2.Enabled = True
End If
End Sub
Private Sub Timer2_Timer()
Timer2.Enabled = False
Text2.Text = PrintProc(Text1.Text)
End Sub
หน้าตาของ Form
เขียนโดย Oneintel

