?
Solved

finding/closing currently running programs

Posted on 1999-01-25
8
Medium Priority
?
165 Views
Last Modified: 2013-12-26
can someone please explain to me how to get a list of all the currently running programs and then how to close certain programs that i wish to close.

can u please give code examples so i can understand and if there is a vb sample program of how to do this somewhere...can u please tell me where to get this.

thanks
0
Comment
Question by:wormboy__6
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 12

Expert Comment

by:mark2150
ID: 1489964
Wormboy__6, the more of your questions I read the less I like what I think you're trying to do!

M

0
 

Author Comment

by:wormboy__6
ID: 1489965
well im sorry if u think im trying to do anything malicious but i just want to know some answers to questions.

ok then...can someone just tell me how to find out the hwnd values of all the process' running....and if u feel like it....say how to close these process'

thanx
0
 
LVL 5

Expert Comment

by:heathprovost
ID: 1489966
Look, I dont really write much code in VB, but I do know how to do what you want.  I am posting some object pascal code for you that does what you want, you can translate it to VB.  It is all API calls unless noted so you should be able to figure it out.  I am not being greedy, but if you want me to convert it to VB you will have to come up with more than 50 points (I am kinda busy right now).  Anyway here it is:

>>>>>>>>>>>>Code starts

program KILLAPPS;

uses Windows, Messages, TlHelp32, SysUtils;

var
  ProcessHandle: THandle;
      ProcessSnap: THandle;
  ProcessEntry32: TProcessEntry32;
  ExeName: String;
  More: Boolean;
  TermResult: Boolean;
  I: integer;
begin
  try
        ProcessSnap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if ProcessSnap = -1 then Exit;
    ProcessEntry32.dwSize := SizeOf(ProcessEntry32);
    More := Process32First(ProcessSnap, ProcessEntry32);
    while More do
    begin
      for I := 1 to ParamCount do ////ParamCount is a Delphi thing, not an API - it just gets command line parameters
      begin
        ExeName := UpperCase(ExtractFileName(ProcessEntry32.szExeFile));
        if ExeName = UpperCase(ParamStr(I)) then
        begin
          ProcessHandle := OpenProcess(PROCESS_TERMINATE, FALSE, ProcessEntry32.th32ProcessID);
          TerminateProcess(ProcessHandle, 0);
          CloseHandle(ProcessHandle);
          break;
        end;
      end;
        More := Process32Next(ProcessSnap, ProcessEntry32);
    end;
  finally
    CloseHandle(ProcessSnap);
end;

end.

>>>>>>>>>>>code ends

BTW - This only works on Windows 95/98 not NT

I hope this helps ya

Heath
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:wormboy__6
ID: 1489967
more than 50 points eh.....
and how much more do u want....heheh i only have 136 left...

0
 
LVL 7

Expert Comment

by:Inteqam
ID: 1489968
does this apply for closin a crystal report form from inside visual basic ?

0
 
LVL 3

Accepted Solution

by:
Foyal earned 100 total points
ID: 1489969
The answer to this and most of your other posted questions can be found in the book:

Visual Basic 5.0 Programmers Guide to the Win32API
by Dan Appleman. ISBN 1-56276-446-2 (about $60.00)

This book is a must have for all VB programmers. It also comes with a CD full of code and other goodies.
0
 
LVL 3

Expert Comment

by:jjmartin
ID: 1489970
Here is some code that will retrieve all the windows that are open.  If this isn't clear enough, if you want to post your email address, I can email you a project that uses this code and will make things easier to understand.  Below is a global function and the windows API declares.

Type wndClass
    style As Long
    lpfnwndproc As Long
    cbClsextra As Long
    cbWndExtra2 As Long
    hInstance As Long
    hIcon As Long
    hCursor As Long
    hbrBackground As Long
    lpszMenuName As String
    lpszClassName As String
End Type

'C language TypeDef to hold the size information for a given window.
Type RECT
        Left As Long
        Top As Long
        Right As Long
        Bottom As Long
End Type


'API Declares
Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, _
                                                        lpdwProcessId As Long) As Long

Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long

Declare Function GetClassLong Lib "user32" Alias "GetClassLongA" (ByVal hwnd As Long, _
                                                                  ByVal nIndex As Long) As Long

Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, _
                                                                   ByVal lpWindowName As String) As Long
                                                                                         
Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, _
                                                                  ByVal lpClassName As String, _
                                                                  ByVal nMaxCount As Long) _
                                                                  As Long

Declare Function GetDesktopWindow Lib "user32" () As Long

Declare Function GetWindow Lib "user32" (ByVal hwnd As Long, ByVal wCmd As Long) As Long

Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, _
                                                                        ByVal lpString As String, ByVal cch As Long) _
                                                                        As Long

Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, _
                                                                    ByVal dwNewLong As Long) As Long

Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal _
                                                  hWndInsertAfter As Long, ByVal X As Long, _
                                                  ByVal Y As Long, ByVal cx As Long, ByVal cy As Long, _
                                                  ByVal wFlags As Long) As Long

Declare Function GetActiveWindow Lib "user32" () As Long

Declare Function BringWindowToTop Lib "user32" (ByVal hwnd As Long) As Long

Declare Function GetForegroundWindow Lib "user32" () As Long

Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, _
                                                                ByVal wMsg As Long, ByVal wParam As Long, _
                                                                lParam As Any) As Long

Declare Function GetClassInfo Lib "user32" Alias "GetClassInfoA" (ByVal hInstance As Long, _
                                                                  ByVal lpClassName As String, _
                                                                  lpWndClass As wndClass) As Long

'----------------------------------------------------------------------------------------------------------
Public Const WM_ACTIVATE = &H6
Public Const SWP_NOMOVE = &H2
Public Const SWP_NOSIZE = &H1
Public Const HWND_TOPMOST = -1
Public Const GW_CHILD = 5
Public Const GW_HWNDNEXT = 2
'----------------------------------------------------------------------------------------------------------



Public Function GetOpenWindowNames() As Long
'----------------------------------------------------------------------------------------------------------
'Name:        Function GetOpenWindowNames()
'
'Purpose:     To retrieve all open windows in the system.
'
'Parameters:  N/A
'
'Return:      NONE
'----------------------------------------------------------------------------------------------------------

'Declare local variables
Dim lngDeskTopHandle As Long    'Used to hold the value of the Desktop handle.
Dim lngHand As Long             'Used to hold each windows handle as it loops.
Dim strName As String * 255     'Fixed length string passed to GetWindowText API call.
Dim lngWindowCount As Long      'Counter used to return the numberof open windows in the system.

'Get the handle for the desktop.
lngDeskTopHandle = GetDesktopWindow()

'Get the first child of the desktop window.
'(Note: The desktop is the parent of all windows in the system.
lngHand = GetWindow(lngDeskTopHandle, GW_CHILD)

'set the window counter to 1.
lngWindowCount = 1

'Loop while there are still open windows.
Do While lngHand <> 0
     
     'Get the title of the next window in the window list.
     GetWindowText lngHand, strName, Len(strName)
     
     'Get the sibling of the current window.
     lngHand = GetWindow(lngHand, GW_HWNDNEXT)
     
     'Make sure the window has a title; and if it does add it to the list.
     If Left$(strName, 1) <> vbNullChar Then
          frmClassFinder.lstOpenWindows.AddItem Left$(strName, InStr(1, strName, vbNullChar))
          lngWindowCount = lngWindowCount + 1
     End If
Loop

'Return the number of windows opened.
GetOpenWindowNames = lngWindowCount

End Function

0
 
LVL 5

Expert Comment

by:heathprovost
ID: 1489971
Well, I thought about it a while and I figured I would need this code myself for something eventually.  So I rewrote it in VB (I am not so busy as I was before :)  )  This code uses the TollHelp32 library of Windows95/98.  I include ALL relevent declarations, although you only need 3 or 4 of them to do what you want.  Anyway, This should do the trick for you.  This is a module by the way.  You need to paste it into one to use it.

>>>>>>>>>>>>>>>CODE STARTS HERE

Option Explicit

Public Const MAX_MODULE_NAME32 As Integer = 255
Public Const MAX_PATH As Integer = 260
Public Const TH32CS_SNAPHEAPLIST As Long = 1&
Public Const TH32CS_SNAPPROCESS As Long = 2&
Public Const TH32CS_SNAPTHREAD As Long = 4&
Public Const TH32CS_SNAPMODULE As Long = 8&
Public Const TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST Or TH32CS_SNAPPROCESS Or TH32CS_SNAPTHREAD Or TH32CS_SNAPMODULE
Public Const TH32CS_INHERIT As Long = 8&
Public Const HF32_DEFAULT As Long = 1&
Public Const HF32_SHARED As Long = 2&
Public Const LF32_FIXED As Long = 1&
Public Const LF32_FREE As Long = 2&
Public Const LF32_MOVEABLE As Long = 4&
Public Const PROCESS_TERMINATE As Long = 1&

Public Type HEAPLIST
    dwSize As Long
    th32ProcessID As Long
    th32HeapId As Long
    dwFlags As Long
End Type

Public Type HEAPENTRY
    dwSize As Long
    hHandle As Long
    dwAddress As Long
    dwBlockSize As Long
    dwFlags As Long
    dwLockCount As Long
    dwResvd As Long
    th32ProcessID As Long
    th32HeapId As Long
End Type

Public Type PROCESSENTRY
    dwSize As Long
    cntUsage As Long
    th32ProcessID As Long
    th32DefaultHeapID As Long
    th32ModuleID As Long
    cntThreads As Long
    th32ParentProcessID As Long
    pcPriClassBase As Long
    dwFlags As Long
    szExeFile As String * MAX_PATH
End Type

Public Type THREADENTRY
    dwSize As Long
    cntUsage As Long
    th32ThreadID As Long
    th32OwnerProcessID As Long
    tpBasePri As Long
    tpDeltaPri As Long
    dwFlags As Long
End Type

Public Type MODULEENTRY
    dwSize As Long
    th32ModuleID As Long
    th32ProcessID As Long
    GlblcntUsage As Long
    ProccntUsage As Long
    modBaseAddr As Long
    modBaseSize As Long
    hModule As Long
    szModule As String * MAX_MODULE_NAME32
    szExePath As String * MAX_PATH
End Type
 
Public Declare Function CreateToolhelpSnapshot Lib "kernel32" Alias "CreateToolhelp32Snapshot" (ByVal dwFlags As Long, ByVal dwProcessID As Long) As Long
Public Declare Function HeapListFirst Lib "kernel32" Alias "Heap32ListFirst" (ByVal hSnapShot As Long, lphl As HEAPLIST) As Long
Public Declare Function HeapListNext Lib "kernel32" Alias "Heap32ListNext" (ByVal hSnapShot As Long, lphl As HEAPLIST) As Long
Public Declare Function HeapFirst Lib "kernel32" Alias "Heap32First" (ByRef lphe As HEAPENTRY, ByVal dwProcessID As Long, ByVal dwHeapId As Long) As Long
Public Declare Function HeapNext Lib "kernel32" Alias "Heap32Next" (ByRef lphe As HEAPENTRY) As Long
Public Declare Function ToolhelpReadProcessMem Lib "kernel32" Alias "Toolhelp32ReadProcessMemory" (ByVal dwProcessID As Long, ByVal lpBaseAddress As Long, ByRef lpBuffer As Long, ByVal cbRead As Long, ByRef lpNumberOfBytesRead As Long) As Long
Public Declare Function ProcessFirst Lib "kernel32" Alias "Process32First" (ByVal hSnapShot As Long, lppe As PROCESSENTRY) As Long
Public Declare Function ProcessNext Lib "kernel32" Alias "Process32Next" (ByVal hSnapShot As Long, lppe As PROCESSENTRY) As Long
Public Declare Function ThreadFirst Lib "kernel32" Alias "Thread32First" (ByVal hSnapShot As Long, lpte As THREADENTRY) As Long
Public Declare Function ThreadNext Lib "kernel32" Alias "Thread32Next" (ByVal hSnapShot As Long, lpte As THREADENTRY) As Long
Public Declare Function ModuleFirst Lib "kernel32" Alias "Module32First" (ByVal hSnapShot As Long, lpme As MODULEENTRY) As Long
Public Declare Function ModuleNext Lib "kernel32" Alias "Module32Next" (ByVal hSnapShot As Long, lpme As MODULEENTRY) As Long
Public Declare Function TerminateProcess Lib "kernel32" (ByVal hProcess As Long, ByVal uExitCode As Long) As Long
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

'This fills a listbox with the names of all running processes
'I added this as an example of how to use this stuff
Sub FillListBoxWithProcessNames(List As ListBox)
    Dim hSnapShot As Long
    Dim uProcess As PROCESSENTRY
    Dim r As Long
    List.Clear
    hSnapShot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
    If hSnapShot = 0 Then Exit Sub
    uProcess.dwSize = Len(uProcess)
    r = ProcessFirst(hSnapShot, uProcess)
    Do While r
        List.AddItem uProcess.szExeFile
        r = ProcessNext(hSnapShot, uProcess)
    Loop
    Call CloseHandle(hSnapShot)
End Sub

'This kills the app passed in by appname.  AppName is the full
'path and filename of the running application.  The way to use
'this with the previous procedure is to call this sub on the
'double click event of the listbox (that you filled earlier)
'Passing in the currently selected item.  I will give
'example after this stuff
Sub KillAppByName(AppName As String)
    Dim hProcess As Long
    Dim hSnapShot As Long
    Dim uProcess As PROCESSENTRY
    Dim MyString As String
    Dim MyPos As Integer
    Dim r As Long
        hSnapShot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
        If hSnapShot = 0 Then Exit Sub
        uProcess.dwSize = Len(uProcess)
        r = ProcessFirst(hSnapShot, uProcess)
        Do While r
            MyPos = InStr(uProcess.szExeFile, Chr(0))
            MyString = Left(uProcess.szExeFile, MyPos - 1)
            If StrComp(MyString, Trim(AppName), vbTextCompare) = 0 Then
                hProcess = OpenProcess(PROCESS_TERMINATE, 0, uProcess.th32ProcessID)
                If hProcess <> 0 Then
                  Call TerminateProcess(hProcess, 0)
                  Call CloseHandle(hProcess)
                End If
                Exit Do
            End If
            r = ProcessNext(hSnapShot, uProcess)
        Loop
    Call CloseHandle(hSnapShot)
End Sub

>>>>>>>>>>>>>>>>END CODE

Here is a simple example.  Place a command button and a listbox on a form and paste this code into it

>>>>>>>>>>>>>>>>>CODE STARTS

Option Explicit

Private Sub Command1_Click()
  FillListBoxWithProcessNames List1
End Sub

Private Sub List1_DblClick()
Dim FileName As String * MAX_PATH
  FileName = List1.List(List1.ListIndex)
  KillAppByName FileName
End Sub

>>>>>>>>>>>>CODE ENDS

This should do what you want.  By the way, this method lets you kill processes regardless of whether they have a window handle or not (not all processes do!).  It is far more reliable and simpler than enumerating all of the open windows to get there handles.  Have fun

Heath
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.   There is also a companion Debug Toolbar that looks like the followin…
Have you ever wanted to restrict the users input in a textbox to numbers, and while doing that make sure that they can't 'cheat' by pasting in non-numeric text? Of course you can do that with code you write yourself but it's tedious and error-prone …
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses
Course of the Month14 days, 18 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question