VB删除自身

注意:这个代码不要在VB的IDE环境中执行.否则将删除VB6.EXE

API:GetModuleFileName 
获取当前进程已加载模块的文件的完整路径,该模块必须由当前进程加载。
如果想要获取另一个已加载模块的文件路径,可以使用GetModuleFileNameEx函数
Private Declare Function GetModuleFileName Lib "kernel32" Alias "GetModuleFileNameA" (ByVal hModule As Long, ByVal lpFileName As String, ByVal nSize As Long) As Long

     'Better than App.EXEName because it also   gets the extension
     '(It's possible to run a program with any extension, not just .exe)


Private Function FullAppName() As String
     Dim modName As String * 256
     Dim i As Long
     i = GetModuleFileName(App.hInstance, modName, Len(modName))
     FullAppName = Left$(modName, i)
End Function


Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
     'All these batch file commands
     'ensure that your program has
     'completely unloaded and
     'is not in use,
     'so your program can be
     'successfully deleted
     'Create a batch file to write to
     Open "a.bat" For Output As #1
     'This is pretty pointless but I
     'just want to put it here
     Print #1, "@ECHO OFF"
     'Create a label to mark the start
     'of the batch file
     Print #1, ":START"
     'If your program doesn't exist,
     'it goes to the FILENOTFOUND label
     Print #1, "IF NOT EXIST " & Chr(34) & FullAppName & Chr(34) & " GOTO FILENOTFOUND"
     'If the file is found, try to
     'delete it
     Print #1, "DEL " & Chr(34) & FullAppName & Chr(34)
     'Repeat the steps
     Print #1, "GOTO START"
     'If the file isn't found,
     'then that means your program
     'has been deleted
     Print #1, ":FILENOTFOUND"
     'Delete the batch file
     '(Batch files can delete
     'themselves while they're
     'still running)
     Print #1, "DEL A.BAT"
     'Clean everything up
     Print #1, "CLS"
     'Exit the batch file
     Print #1, "EXIT"
     'Close the file
     Close #1
     'Finally, execute the
     'batch file, since we only
     'wrote the commands, not ran
     'them
     Shell "a.bat", vbHide
     'Exit this program
     End
End Sub

posted @ 2014-04-08 13:33  iseaside  阅读(552)  评论(0)    收藏  举报