Code Select
'********************************************************************
' KillProcess.bas
'
' Demonstrates how to terminate a running process
'
' Author: Armando I. Rivera (AIR)
' Date: 2025-03-04
' NOTE: If you wish to terminate a process running at the system
' level, you will have to execute this with admin rights.
'
' Compiles with PellesC, MinGW, and MSVC
'********************************************************************
Function main(argc as integer, argv as pchar ptr)
Dim As String processName
if ARGC < 2 then print "Usage: ", appexename$, " <Name of process to terminate>": end = 1
processName = command$(1)
Dim result = KillProcess(processName)
End Function
$HEADER
#include <tlhelp32.h>
$HEADER
Function KillProcess(filename$) As Integer
Dim As DWORD processPID = 0
Dim As HANDLE hSnapshot, hProcess
Dim As PROCESSENTRY32 pe32
Dim As BOOL found = FALSE
Dim As Integer result = 0
' Take a snapshot of all processes
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
If hSnapshot = INVALID_HANDLE_VALUE Then
Print "Failed to create process snapshot. Error: ", GetLastError()
Return 1
End If
' Set the size of the structure before using it
pe32.dwSize = sizeof(PROCESSENTRY32)
' Get the first process
If Not Process32First(hSnapshot, &pe32) Then
Print "Failed to get first process. Error: ", GetLastError()
CloseHandle(hSnapshot);
Return 2
End IF
' Find the process
Do
If pe32.szExeFile$ = filename$ Then
processPID = pe32.th32ProcessID
found = TRUE
Exit Do
End IF
Loop While Process32Next(hSnapshot, &pe32)
CloseHandle(hSnapshot)
If Not found Then
Print filename$," process not found"
Return 3
End If
' Open the requested process
hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, processPID)
If hProcess = NULL Then
print "Failed to open ", filename$, " process. Error: ", GetLastError()
return 4
End If
' Terminate the requested process
If Not TerminateProcess(hProcess, 0) Then
print "Failed to terminate ", filename$, " process. Error: ", GetLastError()
CloseHandle(hProcess)
Return 5
End If
CloseHandle(hProcess)
print filename$," terminated successfully."
' Wait a moment to ensure the process is fully terminated
Sleep(1000)
Return result
End Function
I needed something like this at work today, and threw this together....
AIR.