VB结束进程的代码

前端之家收集整理的这篇文章主要介绍了VB结束进程的代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
朋友用VB开发磅房的监控系统,那个代码写的真是惊天地泣鬼神。不过50岁左右的人从开始学编程到写出来这样的系统并且销售也就用来3、4年的时间,实在也让人佩服。它的系统在导出EXCEL的报表后,系统中会留下EXCEL的进程无法退出。由于家里的事没有帮他去实地解决,就帮他写了一个简单的结束进程的函数让它去调用,把代码贴到这里吧。
Option Explicit

Private Declare Function CreateToolhelp32Snapshot Lib "kernel32" (ByVal dwFlags As Long,ByVal th32ProcessID As Long) As Long
Private Declare Function Process32First Lib "kernel32" (ByVal hSnapshot As Long,lppe As PROCESSENTRY32) As Long
Private Declare Function Process32Next Lib "kernel32" (ByVal hSnapshot As Long,lppe As PROCESSENTRY32) 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 blnheritHandle As Long,ByVal dwAppProcessId As Long) As Long

Private Declare Function TerminateProcess Lib "kernel32" (ByVal ApPHProcess As Long,ByVal uExitCode As Long) As Long

Private Type PROCESSENTRY32
    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 * 1024
End Type

Const TH32CS_SNAPHEAPLIST = &H1
Const TH32CS_SNAPPROCESS = &H2
Const TH32CS_SNAPTHREAD = &H4
Const TH32CS_SNAPMODULE = &H8
Const TH32CS_SNAPALL = (TH32CS_SNAPHEAPLIST Or TH32CS_SNAPPROCESS Or TH32CS_SNAPTHREAD Or TH32CS_SNAPMODULE)
Const TH32CS_INHERIT = &H80000000
Dim pid As Long
Dim pname As String

Public Sub TaskKill(ByVal strTaskName As String)
    Dim pe32 As PROCESSENTRY32
    Dim SnapShot As Long
    Dim flag As Boolean
    Dim mName As String
    Dim i As Integer
    
    If strTaskName = "" Then
        MsgBox "请输入欲结束的进程的名称",vbDefaultButton1,vbOK
        Exit Sub
    End If
    
    SnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0)
    If SnapShot Then
        pe32.dwSize = 1060
        If (Process32First(SnapShot,pe32)) Then
            Do
                i = InStr(1,pe32.szExeFile,Chr$(0))
                mName = LCase$(Left$(pe32.szExeFile,i - 1))
                If mName = LCase$(strTaskName) Then
                    pid = pe32.th32ProcessID
                    pname = mName
                    Dim mProcID As Long
                    
                    mProcID = OpenProcess(1&,-1&,pid)
                    TerminateProcess mProcID,0&
                    flag = True
                Else
                    flag = False
                End If
            Loop Until (Process32Next(SnapShot,pe32) < 1)
            CloseHandle SnapShot
        End If
    End If
End Sub
原文链接:https://www.f2er.com/vb/258747.html

猜你在找的VB相关文章