Hi,
Ok, I've learned how to launch a program (or open any file) from VB. Now, can anyone tell me how to close programs from VB? If I have the path of the program running, can I close it?
Thanks
Printable View
Hi,
Ok, I've learned how to launch a program (or open any file) from VB. Now, can anyone tell me how to close programs from VB? If I have the path of the program running, can I close it?
Thanks
Take a look at this thread (Megatron shows how to find a window by it's caption and then close it).
Or close it by knowing the file path of the exe: App List and Kill
You could also Shell out a Process and wait for it to end.
If the title is variable, (i.e Notepad) then you can close it by it's ClassName instead.
Code:Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) 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_CLOSE = &H10
Const WM_DESTROY = &H2
Private Sub Command1_Click()
'Get the hWnd of the App (by it's ClassName)
hParent = FindWindow("Notepad", vbNullString)
'If it's found then close it
If hParent <> 0 Then
SendMessage hParent, WM_CLOSE, 0, 0
SendMessage hParent, WM_CLOSE, 0, 0
End If
End Sub
Er...Megatron, shouldn't that second WM_CLOSE be WM_DESTROY?
Yes, that's correct. I must have forgot to change it because I copied and pasted the previous line.
Thanks all, but is there some code that can close down an app if I have the file path of the exe? I've looked at the App List and Kill example, but it's kind of confusing to me (I'm a newbie).
I just need code to kill an app (knowing the file path of the exe), I don't need code that lists all the running apps.
Thanks.
Slightly modified version of the KillApp function:
Just call KillApp "c:\myapp\myapp.exe" to kill.Code:Public Function KillApp(myName As String) As Boolean
Const PROCESS_ALL_ACCESS = 0
Dim uProcess As PROCESSENTRY32
Dim rProcessFound As Long
Dim hSnapshot As Long
Dim szExename As String
Dim exitCode As Long
Dim myProcess As Long
Dim AppKill As Boolean
Dim appCount As Integer
Dim i As Integer
On Local Error GoTo Finish
appCount = 0
Const TH32CS_SNAPPROCESS As Long = 2&
uProcess.dwSize = Len(uProcess)
hSnapshot = CreateToolhelpSnapshot(TH32CS_SNAPPROCESS, 0&)
rProcessFound = ProcessFirst(hSnapshot, uProcess)
Do While rProcessFound
i = InStr(1, uProcess.szexeFile, Chr(0))
szExename = LCase$(Left$(uProcess.szexeFile, i - 1))
If Right$(szExename, Len(myName)) = LCase$(myName) Then
KillApp = True
appCount = appCount + 1
myProcess = OpenProcess(PROCESS_ALL_ACCESS, False, uProcess.th32ProcessID)
AppKill = TerminateProcess(myProcess, exitCode)
Call CloseHandle(myProcess)
End If
rProcessFound = ProcessNext(hSnapshot, uProcess)
Loop
Call CloseHandle(hSnapshot)
Finish:
End Function
I'm sure this could be trimmed down further, though.