ПроцессЫЫЫ!

Программирование на Visual Basic, главный форум. Обсуждение тем программирования на VB 1—6.
Даже если вы плохо разбираетесь в VB и программировании вообще — тут вам помогут. В разумных пределах, конечно.
Правила форума
Темы, в которых будет сначала написано «что нужно сделать», а затем просьба «помогите», будут закрыты.
Читайте требования к создаваемым темам.
_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

ПроцессЫЫЫ!

Сообщение _Мика_ » 17.02.2005 (Чт) 19:41

Задача таковА:!
1. получаем список процессов
2. выбираем из списка нужный
3. определяем директорию запущенного файла(найденного процесса)
4. убиваем процесс
5. удаляем файл

ну 1,2,4,5-знаю
3-не знаю

Плиз хелп :roll:
Последний раз редактировалось _Мика_ 17.02.2005 (Чт) 19:58, всего редактировалось 1 раз.
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

neic
Жираф
Жираф
 
Сообщения: 492
Зарегистрирован: 13.02.2005 (Вс) 23:44
Откуда: Сланцы

Сообщение neic » 17.02.2005 (Чт) 19:57

Удаляем файл, или останвливаем процес?

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 19:58

neic писал(а):Удаляем файл, или останвливаем процес?
3. определяем директорию запущенного файла(найденного процесса)
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 20:21

И еще вопрос:
сколько тот или иной процесс жрет памяти, сколько байт проситал и сколько записал! :roll:
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

tyomitch
Пользователь #1352
Пользователь #1352
Аватара пользователя
 
Сообщения: 12822
Зарегистрирован: 20.10.2002 (Вс) 17:02
Откуда: חיפה

Сообщение tyomitch » 17.02.2005 (Чт) 21:01

Ответ на вопрос 3 - GetModuleFileNameEx (Win2000+), можно через Toolhelp32, но дольше.

Ответ на вопрос про память: GetProcessWorkingSetSize

Сколько байт прочитал и сколько записал - не знаю.
Изображение

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 21:11

ШШпасибо, ща посмотрим.....
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 21:37

Need Help with this API! please..... help....
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

A.A.Z.
Член-корреспондент академии VBStreets
Член-корреспондент академии VBStreets
 
Сообщения: 3035
Зарегистрирован: 30.06.2003 (Пн) 13:38

Сообщение A.A.Z. » 17.02.2005 (Чт) 21:59

Код: Выделить всё
'Remark: If you're using VB4 or VB5, you should first uncomment
' the Replace function (on the end of the code)

'In a form
Private Sub Form_Load()
    'Code submitted by Roger Taylor
    'enumerate all the different explorer.exe processes
    GetProcesses "explorer.exe"
End Sub

'In a module

Public Declare Function GetProcessMemoryInfo Lib "PSAPI.DLL" (ByVal hProcess As Long, ppsmemCounters As PROCESS_MEMORY_COUNTERS, ByVal cb As Long) As Long
Public Declare Function Process32First Lib "kernel32" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long
Public Declare Function Process32Next Lib "kernel32" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long
Public Declare Function CloseHandle Lib "Kernel32.dll" (ByVal Handle As Long) As Long
Public Declare Function OpenProcess Lib "Kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId 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 GetModuleFileNameExA Lib "PSAPI.DLL" (ByVal hProcess As Long, ByVal hModule As Long, ByVal ModuleName As String, ByVal nSize As Long) As Long
Public Declare Function EnumProcessModules Lib "PSAPI.DLL" (ByVal hProcess As Long, ByRef lphModule As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long
Public Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal dwFlags As Long, ByVal th32ProcessID As Long) As Long
Public Declare Function GetVersionExA Lib "kernel32" (lpVersionInformation As OSVERSIONINFO) As Integer
Public Declare Function SetTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long) As Long
Public Declare Sub GlobalMemoryStatus Lib "kernel32" (lpBuffer As MEMORYSTATUS)



Public Const PROCESS_QUERY_INFORMATION = 1024
Public Const PROCESS_VM_READ = 16
Public Const MAX_PATH = 260
Public Const STANDARD_RIGHTS_REQUIRED = &HF0000
Public Const SYNCHRONIZE = &H100000
Public Const PROCESS_ALL_ACCESS = &H1F0FFF
Public Const TH32CS_SNAPPROCESS = &H2&
Public Const hNull = 0
Public Const WIN95_System_Found = 1
Public Const WINNT_System_Found = 2
Public Const Default_Log_Size = 10000000
Public Const Default_Log_Days = 0
Public Const SPECIFIC_RIGHTS_ALL = &HFFFF
Public Const STANDARD_RIGHTS_ALL = &H1F0000


Type MEMORYSTATUS
    dwLength As Long
    dwMemoryLoad As Long
    dwTotalPhys As Long
    dwAvailPhys As Long
    dwTotalPageFile As Long
    dwAvailPageFile As Long
    dwTotalVirtual As Long
    dwAvailVirtual As Long
End Type


Type PROCESS_MEMORY_COUNTERS
    cb As Long
    PageFaultCount As Long
    PeakWorkingSetSize As Long
    WorkingSetSize As Long
    QuotaPeakPagedPoolUsage As Long
    QuotaPagedPoolUsage As Long
    QuotaPeakNonPagedPoolUsage As Long
    QuotaNonPagedPoolUsage As Long
    PagefileUsage As Long
    PeakPagefileUsage As Long
End Type


Public Type PROCESSENTRY32
    dwSize As Long
    cntUsage As Long
    th32ProcessID As Long ' This process
    th32DefaultHeapID As Long
    th32ModuleID As Long ' Associated exe
    cntThreads As Long
    th32ParentProcessID As Long ' This process's parent process
    pcPriClassBase As Long ' Base priority of process threads
    dwFlags As Long
    szExeFile As String * 260 ' MAX_PATH
    End Type


Public Type OSVERSIONINFO
    dwOSVersionInfoSize As Long
    dwMajorVersion As Long
    dwMinorVersion As Long
    dwBuildNumber As Long
    dwPlatformId As Long '1 = Windows 95.
    '2 = Windows NT
    szCSDVersion As String * 128
End Type


Public Function GetProcesses(ByVal EXEName As String)

    Dim booResult As Boolean
    Dim lngLength As Long
    Dim lngProcessID As Long
    Dim strProcessName As String
    Dim lngSnapHwnd As Long
    Dim udtProcEntry As PROCESSENTRY32
    Dim lngCBSize As Long 'Specifies the size, In bytes, of the lpidProcess array
    Dim lngCBSizeReturned As Long 'Receives the number of bytes returned
    Dim lngNumElements As Long
    Dim lngProcessIDs() As Long
    Dim lngCBSize2 As Long
    Dim lngModules(1 To 200) As Long
    Dim lngReturn As Long
    Dim strModuleName As String
    Dim lngSize As Long
    Dim lngHwndProcess As Long
    Dim lngLoop As Long
    Dim b As Long
    Dim c As Long
    Dim e As Long
    Dim d As Long
    Dim pmc As PROCESS_MEMORY_COUNTERS
    Dim lret As Long
    Dim strProcName2 As String
    Dim strProcName As String

    'Turn on Error handler
    On Error GoTo Error_handler

   booResult = False

    EXEName = UCase$(Trim$(EXEName))
    lngLength = Len(EXEName)

    'ProcessInfo.bolRunning = False

    Select Case getVersion()
        'I'm not bothered about windows 95/98 becasue this class probably wont be used on it anyway.
        Case WIN95_System_Found 'Windows 95/98

        Case WINNT_System_Found 'Windows NT

            lngCBSize = 8 ' Really needs To be 16, but Loop will increment prior to calling API
            lngCBSizeReturned = 96

            Do While lngCBSize <= lngCBSizeReturned
                DoEvents
                'Increment Size
                lngCBSize = lngCBSize * 2
                'Allocate Memory for Array
                ReDim lngProcessIDs(lngCBSize / 4) As Long
                'Get Process ID's
                lngReturn = EnumProcesses(lngProcessIDs(1), lngCBSize, lngCBSizeReturned)
            Loop

            'Count number of processes returned
            lngNumElements = lngCBSizeReturned / 4
            'Loop thru each process

            For lngLoop = 1 To lngNumElements
            DoEvents

            'Get a handle to the Process and Open
            lngHwndProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, lngProcessIDs(lngLoop))

            If lngHwndProcess <> 0 Then
                'Get an array of the module handles for the specified process
                lngReturn = EnumProcessModules(lngHwndProcess, lngModules(1), 200, lngCBSize2)

                'If the Module Array is retrieved, Get the ModuleFileName
                If lngReturn <> 0 Then

                    'Buffer with spaces first to allocate memory for byte array
                    strModuleName = Space(MAX_PATH)

                    'Must be set prior to calling API
                    lngSize = 500

                    'Get Process Name
                    lngReturn = GetModuleFileNameExA(lngHwndProcess, lngModules(1), strModuleName, lngSize)

                    'Remove trailing spaces
                    strProcessName = Left(strModuleName, lngReturn)

                    'Check for Matching Upper case result
                    strProcessName = UCase$(Trim$(strProcessName))

                    strProcName2 = GetElement(Trim(Replace(strProcessName, Chr$(0), "")), "\", 0, 0, GetNumElements(Trim(Replace(strProcessName, Chr$(0), "")), "\") - 1)

                    If strProcName2 = EXEName Then

                        'Get the Site of the Memory Structure
                        pmc.cb = LenB(pmc)

                           lret = GetProcessMemoryInfo(lngHwndProcess, pmc, pmc.cb)

                            Debug.Print EXEName & "::" & CStr(pmc.WorkingSetSize / 1024)

                    End If
                End If
            End If
            'Close the handle to this process
            lngReturn = CloseHandle(lngHwndProcess)
            DoEvents
        Next

    End Select

IsProcessRunning_Exit:

'Exit early to avoid error handler
Exit Function
Error_handler:
    Err.Raise Err, Err.Source, "ProcessInfo", Error
    Resume Next
End Function


Private Function getVersion() As Long

    Dim osinfo As OSVERSIONINFO
    Dim retvalue As Integer

    osinfo.dwOSVersionInfoSize = 148
    osinfo.szCSDVersion = Space$(128)
    retvalue = GetVersionExA(osinfo)
    getVersion = osinfo.dwPlatformId

End Function


Private Function StrZToStr(s As String) As String
    StrZToStr = Left$(s, Len(s) - 1)
End Function



Public Function GetElement(ByVal strList As String, ByVal strDelimiter As String, ByVal lngNumColumns As Long, ByVal lngRow As Long, ByVal lngColumn As Long) As String

    Dim lngCounter As Long

    ' Append delimiter text to the end of the list as a terminator.
    strList = strList & strDelimiter

    ' Calculate the offset for the item required based on the number of columns the list
    ' 'strList' has i.e. 'lngNumColumns' and from which row the element is to be
    ' selected i.e. 'lngRow'.
    lngColumn = IIf(lngRow = 0, lngColumn, (lngRow * lngNumColumns) + lngColumn)

    ' Search for the 'lngColumn' item from the list 'strList'.
    For lngCounter = 0 To lngColumn - 1

        ' Remove each item from the list.
        strList = Mid$(strList, InStr(strList, strDelimiter) + Len(strDelimiter), Len(strList))

        ' If list becomes empty before 'lngColumn' is found then just
        ' return an empty string.
        If Len(strList) = 0 Then
            GetElement = ""
            Exit Function
        End If

    Next lngCounter

    ' Return the sought list element.
    GetElement = Left$(strList, InStr(strList, strDelimiter) - 1)

End Function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Function GetNumElements (ByVal strList As String,
'                         ByVal strDelimiter As String)
'                         As Integer
'
'  strList      = The element list.
'  strDelimiter = The delimiter by which the elements in
'                 'strList' are seperated.
'
'  The function returns an integer which is the count of the
'  number of elements in 'strList'.
'
'  Author: Roger Taylor
'
'  Date:26/12/1998
'
'  Additional Information:
'
'  Revision History:
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Public Function GetNumElements(ByVal strList As String, ByVal strDelimiter As String) As Integer

    Dim intElementCount As Integer

    ' If no elements in the list 'strList' then just return 0.
    If Len(strList) = 0 Then
        GetNumElements = 0
        Exit Function
    End If

    ' Append delimiter text to the end of the list as a terminator.
    strList = strList & strDelimiter

    ' Count the number of elements in 'strlist'
    While InStr(strList, strDelimiter) > 0
        intElementCount = intElementCount + 1
        strList = Mid$(strList, InStr(strList, strDelimiter) + 1, Len(strList))
    Wend

    ' Return the number of elements in 'strList'.
    GetNumElements = intElementCount

End Function


'If you're using VB4 or VB5, uncomment the following function:
'Function Replace(sInput As String, WhatToReplace As String, ReplaceWith As String) As String
    'Dim Ret As Long
    'Replace = sInput
    'Ret = -Len(ReplaceWith) + 1
    'Do
        'Ret = InStr(Ret + Len(ReplaceWith), Replace, WhatToReplace, vbTextCompare)
        'If Ret = 0 Then Exit Do
        'Replace = Left$(Replace, Ret - 1) + ReplaceWith + Right$(Replace, Len(Replace) - Ret - Len(WhatToReplace) + 1)
    'Loop
'End Function

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 22:04

A.A.Z. писал(а):
Код: Выделить всё
'Remark: If you're using VB4 or VB5, you should first uncomment
' the Replace function (on the end of the code)

'In a form
Private Sub Form_Load()
    'Code submitted by Roger Taylor
    'enumerate all the different explorer.exe processes
    GetProcesses "explorer.exe"
End Sub

'In a module

Public Declare Function GetProcessMemoryInfo Lib "PSAPI.DLL" (ByVal hProcess As Long, ppsmemCounters As PROCESS_MEMORY_COUNTERS, ByVal cb As Long) As Long
Public Declare Function Process32First Lib "kernel32" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long
Public Declare Function Process32Next Lib "kernel32" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long
Public Declare Function CloseHandle Lib "Kernel32.dll" (ByVal Handle As Long) As Long
Public Declare Function OpenProcess Lib "Kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId 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 GetModuleFileNameExA Lib "PSAPI.DLL" (ByVal hProcess As Long, ByVal hModule As Long, ByVal ModuleName As String, ByVal nSize As Long) As Long
Public Declare Function EnumProcessModules Lib "PSAPI.DLL" (ByVal hProcess As Long, ByRef lphModule As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long
Public Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal dwFlags As Long, ByVal th32ProcessID As Long) As Long
Public Declare Function GetVersionExA Lib "kernel32" (lpVersionInformation As OSVERSIONINFO) As Integer
Public Declare Function SetTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long) As Long
Public Declare Sub GlobalMemoryStatus Lib "kernel32" (lpBuffer As MEMORYSTATUS)



Public Const PROCESS_QUERY_INFORMATION = 1024
Public Const PROCESS_VM_READ = 16
Public Const MAX_PATH = 260
Public Const STANDARD_RIGHTS_REQUIRED = &HF0000
Public Const SYNCHRONIZE = &H100000
Public Const PROCESS_ALL_ACCESS = &H1F0FFF
Public Const TH32CS_SNAPPROCESS = &H2&
Public Const hNull = 0
Public Const WIN95_System_Found = 1
Public Const WINNT_System_Found = 2
Public Const Default_Log_Size = 10000000
Public Const Default_Log_Days = 0
Public Const SPECIFIC_RIGHTS_ALL = &HFFFF
Public Const STANDARD_RIGHTS_ALL = &H1F0000


Type MEMORYSTATUS
    dwLength As Long
    dwMemoryLoad As Long
    dwTotalPhys As Long
    dwAvailPhys As Long
    dwTotalPageFile As Long
    dwAvailPageFile As Long
    dwTotalVirtual As Long
    dwAvailVirtual As Long
End Type


Type PROCESS_MEMORY_COUNTERS
    cb As Long
    PageFaultCount As Long
    PeakWorkingSetSize As Long
    WorkingSetSize As Long
    QuotaPeakPagedPoolUsage As Long
    QuotaPagedPoolUsage As Long
    QuotaPeakNonPagedPoolUsage As Long
    QuotaNonPagedPoolUsage As Long
    PagefileUsage As Long
    PeakPagefileUsage As Long
End Type


Public Type PROCESSENTRY32
    dwSize As Long
    cntUsage As Long
    th32ProcessID As Long ' This process
    th32DefaultHeapID As Long
    th32ModuleID As Long ' Associated exe
    cntThreads As Long
    th32ParentProcessID As Long ' This process's parent process
    pcPriClassBase As Long ' Base priority of process threads
    dwFlags As Long
    szExeFile As String * 260 ' MAX_PATH
    End Type


Public Type OSVERSIONINFO
    dwOSVersionInfoSize As Long
    dwMajorVersion As Long
    dwMinorVersion As Long
    dwBuildNumber As Long
    dwPlatformId As Long '1 = Windows 95.
    '2 = Windows NT
    szCSDVersion As String * 128
End Type


Public Function GetProcesses(ByVal EXEName As String)

    Dim booResult As Boolean
    Dim lngLength As Long
    Dim lngProcessID As Long
    Dim strProcessName As String
    Dim lngSnapHwnd As Long
    Dim udtProcEntry As PROCESSENTRY32
    Dim lngCBSize As Long 'Specifies the size, In bytes, of the lpidProcess array
    Dim lngCBSizeReturned As Long 'Receives the number of bytes returned
    Dim lngNumElements As Long
    Dim lngProcessIDs() As Long
    Dim lngCBSize2 As Long
    Dim lngModules(1 To 200) As Long
    Dim lngReturn As Long
    Dim strModuleName As String
    Dim lngSize As Long
    Dim lngHwndProcess As Long
    Dim lngLoop As Long
    Dim b As Long
    Dim c As Long
    Dim e As Long
    Dim d As Long
    Dim pmc As PROCESS_MEMORY_COUNTERS
    Dim lret As Long
    Dim strProcName2 As String
    Dim strProcName As String

    'Turn on Error handler
    On Error GoTo Error_handler

   booResult = False

    EXEName = UCase$(Trim$(EXEName))
    lngLength = Len(EXEName)

    'ProcessInfo.bolRunning = False

    Select Case getVersion()
        'I'm not bothered about windows 95/98 becasue this class probably wont be used on it anyway.
        Case WIN95_System_Found 'Windows 95/98

        Case WINNT_System_Found 'Windows NT

            lngCBSize = 8 ' Really needs To be 16, but Loop will increment prior to calling API
            lngCBSizeReturned = 96

            Do While lngCBSize <= lngCBSizeReturned
                DoEvents
                'Increment Size
                lngCBSize = lngCBSize * 2
                'Allocate Memory for Array
                ReDim lngProcessIDs(lngCBSize / 4) As Long
                'Get Process ID's
                lngReturn = EnumProcesses(lngProcessIDs(1), lngCBSize, lngCBSizeReturned)
            Loop

            'Count number of processes returned
            lngNumElements = lngCBSizeReturned / 4
            'Loop thru each process

            For lngLoop = 1 To lngNumElements
            DoEvents

            'Get a handle to the Process and Open
            lngHwndProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, lngProcessIDs(lngLoop))

            If lngHwndProcess <> 0 Then
                'Get an array of the module handles for the specified process
                lngReturn = EnumProcessModules(lngHwndProcess, lngModules(1), 200, lngCBSize2)

                'If the Module Array is retrieved, Get the ModuleFileName
                If lngReturn <> 0 Then

                    'Buffer with spaces first to allocate memory for byte array
                    strModuleName = Space(MAX_PATH)

                    'Must be set prior to calling API
                    lngSize = 500

                    'Get Process Name
                    lngReturn = GetModuleFileNameExA(lngHwndProcess, lngModules(1), strModuleName, lngSize)

                    'Remove trailing spaces
                    strProcessName = Left(strModuleName, lngReturn)

                    'Check for Matching Upper case result
                    strProcessName = UCase$(Trim$(strProcessName))

                    strProcName2 = GetElement(Trim(Replace(strProcessName, Chr$(0), "")), "", 0, 0, GetNumElements(Trim(Replace(strProcessName, Chr$(0), "")), "") - 1)

                    If strProcName2 = EXEName Then

                        'Get the Site of the Memory Structure
                        pmc.cb = LenB(pmc)

                           lret = GetProcessMemoryInfo(lngHwndProcess, pmc, pmc.cb)

                            Debug.Print EXEName & "::" & CStr(pmc.WorkingSetSize / 1024)

                    End If
                End If
            End If
            'Close the handle to this process
            lngReturn = CloseHandle(lngHwndProcess)
            DoEvents
        Next

    End Select

IsProcessRunning_Exit:

'Exit early to avoid error handler
Exit Function
Error_handler:
    Err.Raise Err, Err.Source, "ProcessInfo", Error
    Resume Next
End Function


Private Function getVersion() As Long

    Dim osinfo As OSVERSIONINFO
    Dim retvalue As Integer

    osinfo.dwOSVersionInfoSize = 148
    osinfo.szCSDVersion = Space$(128)
    retvalue = GetVersionExA(osinfo)
    getVersion = osinfo.dwPlatformId

End Function


Private Function StrZToStr(s As String) As String
    StrZToStr = Left$(s, Len(s) - 1)
End Function



Public Function GetElement(ByVal strList As String, ByVal strDelimiter As String, ByVal lngNumColumns As Long, ByVal lngRow As Long, ByVal lngColumn As Long) As String

    Dim lngCounter As Long

    ' Append delimiter text to the end of the list as a terminator.
    strList = strList & strDelimiter

    ' Calculate the offset for the item required based on the number of columns the list
    ' 'strList' has i.e. 'lngNumColumns' and from which row the element is to be
    ' selected i.e. 'lngRow'.
    lngColumn = IIf(lngRow = 0, lngColumn, (lngRow * lngNumColumns) + lngColumn)

    ' Search for the 'lngColumn' item from the list 'strList'.
    For lngCounter = 0 To lngColumn - 1

        ' Remove each item from the list.
        strList = Mid$(strList, InStr(strList, strDelimiter) + Len(strDelimiter), Len(strList))

        ' If list becomes empty before 'lngColumn' is found then just
        ' return an empty string.
        If Len(strList) = 0 Then
            GetElement = ""
            Exit Function
        End If

    Next lngCounter

    ' Return the sought list element.
    GetElement = Left$(strList, InStr(strList, strDelimiter) - 1)

End Function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Function GetNumElements (ByVal strList As String,
'                         ByVal strDelimiter As String)
'                         As Integer
'
'  strList      = The element list.
'  strDelimiter = The delimiter by which the elements in
'                 'strList' are seperated.
'
'  The function returns an integer which is the count of the
'  number of elements in 'strList'.
'
'  Author: Roger Taylor
'
'  Date:26/12/1998
'
'  Additional Information:
'
'  Revision History:
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Public Function GetNumElements(ByVal strList As String, ByVal strDelimiter As String) As Integer

    Dim intElementCount As Integer

    ' If no elements in the list 'strList' then just return 0.
    If Len(strList) = 0 Then
        GetNumElements = 0
        Exit Function
    End If

    ' Append delimiter text to the end of the list as a terminator.
    strList = strList & strDelimiter

    ' Count the number of elements in 'strlist'
    While InStr(strList, strDelimiter) > 0
        intElementCount = intElementCount + 1
        strList = Mid$(strList, InStr(strList, strDelimiter) + 1, Len(strList))
    Wend

    ' Return the number of elements in 'strList'.
    GetNumElements = intElementCount

End Function


'If you're using VB4 or VB5, uncomment the following function:
'Function Replace(sInput As String, WhatToReplace As String, ReplaceWith As String) As String
    'Dim Ret As Long
    'Replace = sInput
    'Ret = -Len(ReplaceWith) + 1
    'Do
        'Ret = InStr(Ret + Len(ReplaceWith), Replace, WhatToReplace, vbTextCompare)
        'If Ret = 0 Then Exit Do
        'Replace = Left$(Replace, Ret - 1) + ReplaceWith + Right$(Replace, Len(Replace) - Ret - Len(WhatToReplace) + 1)
    'Loop
'End Function
Не ужели ты думаешь что этот код не попробовал? Он выдает посто какоето число! А мне нужен путь к файлу!!!
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

A.A.Z.
Член-корреспондент академии VBStreets
Член-корреспондент академии VBStreets
 
Сообщения: 3035
Зарегистрирован: 30.06.2003 (Пн) 13:38

Сообщение A.A.Z. » 17.02.2005 (Чт) 22:12

А разобраться? :)
Добавь на форму Combo1, добавь модуль и вставь код:
Это в форму:
Код: Выделить всё
Private Sub Form_Load()
GetProcesses ""
End Sub

Это в модуль:
Код: Выделить всё
'In a module

Public Declare Function GetProcessMemoryInfo Lib "PSAPI.DLL" (ByVal hProcess As Long, ppsmemCounters As PROCESS_MEMORY_COUNTERS, ByVal cb As Long) As Long
Public Declare Function Process32First Lib "kernel32" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long
Public Declare Function Process32Next Lib "kernel32" (ByVal hSnapshot As Long, lppe As PROCESSENTRY32) As Long
Public Declare Function CloseHandle Lib "Kernel32.dll" (ByVal Handle As Long) As Long
Public Declare Function OpenProcess Lib "Kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId 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 GetModuleFileNameExA Lib "PSAPI.DLL" (ByVal hProcess As Long, ByVal hModule As Long, ByVal ModuleName As String, ByVal nSize As Long) As Long
Public Declare Function EnumProcessModules Lib "PSAPI.DLL" (ByVal hProcess As Long, ByRef lphModule As Long, ByVal cb As Long, ByRef cbNeeded As Long) As Long
Public Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal dwFlags As Long, ByVal th32ProcessID As Long) As Long
Public Declare Function GetVersionExA Lib "kernel32" (lpVersionInformation As OSVERSIONINFO) As Integer
Public Declare Function SetTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long, ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" (ByVal hwnd As Long, ByVal nIDEvent As Long) As Long
Public Declare Sub GlobalMemoryStatus Lib "kernel32" (lpBuffer As MEMORYSTATUS)



Public Const PROCESS_QUERY_INFORMATION = 1024
Public Const PROCESS_VM_READ = 16
Public Const MAX_PATH = 260
Public Const STANDARD_RIGHTS_REQUIRED = &HF0000
Public Const SYNCHRONIZE = &H100000
Public Const PROCESS_ALL_ACCESS = &H1F0FFF
Public Const TH32CS_SNAPPROCESS = &H2&
Public Const hNull = 0
Public Const WIN95_System_Found = 1
Public Const WINNT_System_Found = 2
Public Const Default_Log_Size = 10000000
Public Const Default_Log_Days = 0
Public Const SPECIFIC_RIGHTS_ALL = &HFFFF
Public Const STANDARD_RIGHTS_ALL = &H1F0000


Type MEMORYSTATUS
    dwLength As Long
    dwMemoryLoad As Long
    dwTotalPhys As Long
    dwAvailPhys As Long
    dwTotalPageFile As Long
    dwAvailPageFile As Long
    dwTotalVirtual As Long
    dwAvailVirtual As Long
End Type


Type PROCESS_MEMORY_COUNTERS
    cb As Long
    PageFaultCount As Long
    PeakWorkingSetSize As Long
    WorkingSetSize As Long
    QuotaPeakPagedPoolUsage As Long
    QuotaPagedPoolUsage As Long
    QuotaPeakNonPagedPoolUsage As Long
    QuotaNonPagedPoolUsage As Long
    PagefileUsage As Long
    PeakPagefileUsage As Long
End Type


Public Type PROCESSENTRY32
    dwSize As Long
    cntUsage As Long
    th32ProcessID As Long ' This process
    th32DefaultHeapID As Long
    th32ModuleID As Long ' Associated exe
    cntThreads As Long
    th32ParentProcessID As Long ' This process's parent process
    pcPriClassBase As Long ' Base priority of process threads
    dwFlags As Long
    szExeFile As String * 260 ' MAX_PATH
    End Type


Public Type OSVERSIONINFO
    dwOSVersionInfoSize As Long
    dwMajorVersion As Long
    dwMinorVersion As Long
    dwBuildNumber As Long
    dwPlatformId As Long '1 = Windows 95.
    '2 = Windows NT
    szCSDVersion As String * 128
End Type


Public Function GetProcesses()

    Dim booResult As Boolean
    Dim lngLength As Long
    Dim lngProcessID As Long
    Dim strProcessName As String
    Dim lngSnapHwnd As Long
    Dim udtProcEntry As PROCESSENTRY32
    Dim lngCBSize As Long 'Specifies the size, In bytes, of the lpidProcess array
    Dim lngCBSizeReturned As Long 'Receives the number of bytes returned
    Dim lngNumElements As Long
    Dim lngProcessIDs() As Long
    Dim lngCBSize2 As Long
    Dim lngModules(1 To 200) As Long
    Dim lngReturn As Long
    Dim strModuleName As String
    Dim lngSize As Long
    Dim lngHwndProcess As Long
    Dim lngLoop As Long
    Dim b As Long
    Dim c As Long
    Dim e As Long
    Dim d As Long
    Dim pmc As PROCESS_MEMORY_COUNTERS
    Dim lret As Long
    Dim strProcName2 As String
    Dim strProcName As String

    'Turn on Error handler
    On Error GoTo Error_handler

   booResult = False


    'ProcessInfo.bolRunning = False

    Select Case getVersion()
        'I'm not bothered about windows 95/98 becasue this class probably wont be used on it anyway.
        Case WIN95_System_Found 'Windows 95/98

        Case WINNT_System_Found 'Windows NT

            lngCBSize = 8 ' Really needs To be 16, but Loop will increment prior to calling API
            lngCBSizeReturned = 96

            Do While lngCBSize <= lngCBSizeReturned
                DoEvents
                'Increment Size
                lngCBSize = lngCBSize * 2
                'Allocate Memory for Array
                ReDim lngProcessIDs(lngCBSize / 4) As Long
                'Get Process ID's
                lngReturn = EnumProcesses(lngProcessIDs(1), lngCBSize, lngCBSizeReturned)
            Loop

            'Count number of processes returned
            lngNumElements = lngCBSizeReturned / 4
            'Loop thru each process

            For lngLoop = 1 To lngNumElements
            DoEvents

            'Get a handle to the Process and Open
            lngHwndProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, lngProcessIDs(lngLoop))

            If lngHwndProcess <> 0 Then
                'Get an array of the module handles for the specified process
                lngReturn = EnumProcessModules(lngHwndProcess, lngModules(1), 200, lngCBSize2)

                'If the Module Array is retrieved, Get the ModuleFileName
                If lngReturn <> 0 Then

                    'Buffer with spaces first to allocate memory for byte array
                    strModuleName = Space(MAX_PATH)

                    'Must be set prior to calling API
                    lngSize = 500

                    'Get Process Name
                    lngReturn = GetModuleFileNameExA(lngHwndProcess, lngModules(1), strModuleName, lngSize)

                    'Remove trailing spaces
                    strProcessName = Left(strModuleName, lngReturn)

                    'Check for Matching Upper case result
                    strProcessName = UCase$(Trim$(strProcessName))

                    strProcName2 = GetElement(Trim(Replace(strProcessName, Chr$(0), "")), "\", 0, 0, GetNumElements(Trim(Replace(strProcessName, Chr$(0), "")), "\") - 1)
                   
                    Form1.Combo1.AddItem LCase(strProcName2)
                   
                End If
            End If
            'Close the handle to this process
            lngReturn = CloseHandle(lngHwndProcess)
            DoEvents
        Next

    End Select

IsProcessRunning_Exit:

'Exit early to avoid error handler
Exit Function
Error_handler:
    Err.Raise Err, Err.Source, "ProcessInfo", Error
    Resume Next
End Function


Private Function getVersion() As Long

    Dim osinfo As OSVERSIONINFO
    Dim retvalue As Integer

    osinfo.dwOSVersionInfoSize = 148
    osinfo.szCSDVersion = Space$(128)
    retvalue = GetVersionExA(osinfo)
    getVersion = osinfo.dwPlatformId

End Function


Private Function StrZToStr(s As String) As String
    StrZToStr = Left$(s, Len(s) - 1)
End Function



Public Function GetElement(ByVal strList As String, ByVal strDelimiter As String, ByVal lngNumColumns As Long, ByVal lngRow As Long, ByVal lngColumn As Long) As String

    Dim lngCounter As Long

    ' Append delimiter text to the end of the list as a terminator.
    strList = strList & strDelimiter

    ' Calculate the offset for the item required based on the number of columns the list
    ' 'strList' has i.e. 'lngNumColumns' and from which row the element is to be
    ' selected i.e. 'lngRow'.
    lngColumn = IIf(lngRow = 0, lngColumn, (lngRow * lngNumColumns) + lngColumn)

    ' Search for the 'lngColumn' item from the list 'strList'.
    For lngCounter = 0 To lngColumn - 1

        ' Remove each item from the list.
        strList = Mid$(strList, InStr(strList, strDelimiter) + Len(strDelimiter), Len(strList))

        ' If list becomes empty before 'lngColumn' is found then just
        ' return an empty string.
        If Len(strList) = 0 Then
            GetElement = ""
            Exit Function
        End If

    Next lngCounter

    ' Return the sought list element.
    GetElement = Left$(strList, InStr(strList, strDelimiter) - 1)

End Function


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Function GetNumElements (ByVal strList As String,
'                         ByVal strDelimiter As String)
'                         As Integer
'
'  strList      = The element list.
'  strDelimiter = The delimiter by which the elements in
'                 'strList' are seperated.
'
'  The function returns an integer which is the count of the
'  number of elements in 'strList'.
'
'  Author: Roger Taylor
'
'  Date:26/12/1998
'
'  Additional Information:
'
'  Revision History:
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Public Function GetNumElements(ByVal strList As String, ByVal strDelimiter As String) As Integer

    Dim intElementCount As Integer

    ' If no elements in the list 'strList' then just return 0.
    If Len(strList) = 0 Then
        GetNumElements = 0
        Exit Function
    End If

    ' Append delimiter text to the end of the list as a terminator.
    strList = strList & strDelimiter

    ' Count the number of elements in 'strlist'
    While InStr(strList, strDelimiter) > 0
        intElementCount = intElementCount + 1
        strList = Mid$(strList, InStr(strList, strDelimiter) + 1, Len(strList))
    Wend

    ' Return the number of elements in 'strList'.
    GetNumElements = intElementCount

End Function


'If you're using VB4 or VB5, uncomment the following function:
'Function Replace(sInput As String, WhatToReplace As String, ReplaceWith As String) As String
    'Dim Ret As Long
    'Replace = sInput
    'Ret = -Len(ReplaceWith) + 1
    'Do
        'Ret = InStr(Ret + Len(ReplaceWith), Replace, WhatToReplace, vbTextCompare)
        'If Ret = 0 Then Exit Do
        'Replace = Left$(Replace, Ret - 1) + ReplaceWith + Right$(Replace, Len(Replace) - Ret - Len(WhatToReplace) + 1)
    'Loop
'End Function

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 22:24

Не фурыкает!
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

A.A.Z.
Член-корреспондент академии VBStreets
Член-корреспондент академии VBStreets
 
Сообщения: 3035
Зарегистрирован: 30.06.2003 (Пн) 13:38

Сообщение A.A.Z. » 17.02.2005 (Чт) 22:32

А разобраться?!

Ошибся я, надо было просто
Код: Выделить всё
Sub Form_Load()
GetProcesses
End Sub

И не забудь потом Combo сам открыть!

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 22:55

Ну ето просто все процессы перечесляет, а мне надо у конкретного процесса узнать дирексторию запуска, если так можно выразиться :lol:
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

tyomitch
Пользователь #1352
Пользователь #1352
Аватара пользователя
 
Сообщения: 12822
Зарегистрирован: 20.10.2002 (Вс) 17:02
Откуда: חיפה

Сообщение tyomitch » 17.02.2005 (Чт) 23:00

Мика, неужели тебе приятнее юзать многостраничный модуль, чем одну функцию? Или так важна совместимость с Win98?
Изображение

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 23:27

Так в том то все и дело... просто можно литл примерчик!
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

tyomitch
Пользователь #1352
Пользователь #1352
Аватара пользователя
 
Сообщения: 12822
Зарегистрирован: 20.10.2002 (Вс) 17:02
Откуда: חיפה

Сообщение tyomitch » 17.02.2005 (Чт) 23:35

Легко - и сравни длину!
Код: Выделить всё
Option Explicit

Private Declare Function GetModuleFileNameEx Lib "psapi" Alias "GetModuleFileNameExA" (ByVal hProcess As Long, ByVal hModule As Long, ByVal lpFilename As String, ByVal nSize As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long

Private Const PROCESS_QUERY_INFORMATION = &H400
Private Const PROCESS_VM_READ = &H10


Sub Main()
'PID посмотри Диспетчером задач и подставь сам
Dim PID As Long, hProcess As Long, FileName As String
PID = 2504
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION Or PROCESS_VM_READ, 0, PID)
FileName = Space(255)
FileName = Left(FileName, GetModuleFileNameEx(hProcess, 0, FileName, 255))
CloseHandle hProcess
Debug.Print FileName
End Sub
Изображение

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 17.02.2005 (Чт) 23:57

ГЕНИАЛЬНО, СПАСИБО!!!
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 18.02.2005 (Пт) 0:07

Вот еще бы память, и загрузку процессора... <a href='http://www.smileycentral.com/?partner=ZSzeb008_ZS' target='_blank'><img src='http://smileys.smileycentral.com/cat/36/36_1_12.gif' alt='Wink' border=0></a>
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

tyomitch
Пользователь #1352
Пользователь #1352
Аватара пользователя
 
Сообщения: 12822
Зарегистрирован: 20.10.2002 (Вс) 17:02
Откуда: חיפה

Сообщение tyomitch » 18.02.2005 (Пт) 1:30

Вот, нашёл ввод/вывод: GetProcessIoCounters
Загрузка процессора: GetProcessTimes
Память: GetProcessWorkingSetSize (уже называл)

Неужели не разберёшься сам?
Изображение

GM
programador
programador
 
Сообщения: 1427
Зарегистрирован: 24.06.2003 (Вт) 15:56
Откуда: 194.67.52.100

Сообщение GM » 18.02.2005 (Пт) 8:38

Вырезка с SysManager'a
Код: Выделить всё
Private Declare Function GetProcessIoCounters Lib "kernel32.dll" (ByVal hprocess As Long, ByRef lpIoCounters As PIO_Counters) As Long
Type int64
c1 As Long
c2 As Long
End Type
Type PIO_Counters

ReadOperationCount As int64 'Number of read operations performed.
WriteOperationCount As int64 'Number of write operations performed.
OtherOperationCount As int64  'Number of I/O operations performed, other than read and write operations.
ReadTransferCount As int64 'Number of bytes read.
WriteTransferCount As int64 'Number of bytes written.
OtherTransferCount As int64 'Number of bytes transferred during operations other than read and write operations.

End Type

Dim hprocess As Long
Dim pmc As PIO_Counters
Dim lRet As Long
  hprocess = OpenProcess(PROCESS_QUERY_INFORMATION, 0&, pid)
  lRet = GetProcessIoCounters(hprocess, pmc)

CloseHandle (hprocess)
الفيجوال بيسك الرابح

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 18.02.2005 (Пт) 10:42

tyomitch писал(а):Вот, нашёл ввод/вывод: GetProcessIoCounters
Загрузка процессора: GetProcessTimes
Память: GetProcessWorkingSetSize (уже называл)

Неужели не разберёшься сам?

GetProcessWorkingSetSize эту функцию я не нашел :roll:

GM - спасибо ща ПОРОБУЮ разобраться САМ :D
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

_Мика_
Гуру
Гуру
 
Сообщения: 1459
Зарегистрирован: 24.10.2003 (Пт) 15:05
Откуда: г. Москва, м.Речной вокзал

Сообщение _Мика_ » 18.02.2005 (Пт) 10:44

_Мика_ писал(а):
tyomitch писал(а):Вот, нашёл ввод/вывод: GetProcessIoCounters
Загрузка процессора: GetProcessTimes
Память: GetProcessWorkingSetSize (уже называл)

Неужели не разберёшься сам?

GetProcessWorkingSetSize эту функцию я не нашел :roll:
GetProcessTimes - оннв же показывает сколько времени работала прога? Нет?

GM - спасибо ща ПОРОБУЮ разобраться САМ :D
-Папа, а правда, что форумы делают людей дибилами?
-гы гы гы, сынок, лол!

tyomitch
Пользователь #1352
Пользователь #1352
Аватара пользователя
 
Сообщения: 12822
Зарегистрирован: 20.10.2002 (Вс) 17:02
Откуда: חיפה

Сообщение tyomitch » 18.02.2005 (Пт) 12:47

_Мика_ писал(а):GetProcessWorkingSetSize эту функцию я не нашел :roll:

В смысле?
Код: Выделить всё
Declare Function GetProcessWorkingSetSize Lib "kernel32" (ByVal hProcess As Long, lpMinimumWorkingSetSize As Long, lpMaximumWorkingSetSize As Long) As Long
Изображение


Вернуться в Visual Basic 1–6

Кто сейчас на конференции

Сейчас этот форум просматривают: Yandex-бот и гости: 168

    TopList