How can i Kill a process on Windows 10 by name ?

Just starting out? Need help? Post your questions and find answers here.
User avatar
skinkairewalker
Enthusiast
Enthusiast
Posts: 635
Joined: Fri Dec 04, 2015 9:26 pm

How can i Kill a process on Windows 10 by name ?

Post by skinkairewalker »

hi everyone ! i would like know how can i kill some second plan and first plan applications ...
i found this code , but it just works with windowed application ...

Note > testApplication.exe is a window-less application ... this code works with Calculator.exe

Code: Select all

hWnd = FindWindow_(0, "testApplication.exe")
Debug hWnd
If hWnd <> 0
  Debug "Calculator found"
  Debug "Closing..."
  SendMessage_(hWnd, #WM_CLOSE, 0, 0)
  Debug "Done"
EndIf 
User avatar
skinkairewalker
Enthusiast
Enthusiast
Posts: 635
Joined: Fri Dec 04, 2015 9:26 pm

Re: How can i Kill a process on Windows 10 by name ?

Post by skinkairewalker »

hi everyone ! i am back xD

i found a simple way to do it easy ! 8)

follow code below :D

Code: Select all

ImportC "msvcrt.lib"
  system(str.p-ascii)
EndImport

OpenConsole()
system("tasklist")
 ; i found ir here > https://technet.microsoft.com/pt-br/library/bb491009.aspx
system("taskkill /IM test.exe /F")

Repeat
  
ForEver  
User avatar
Kwai chang caine
Always Here
Always Here
Posts: 5353
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: How can i Kill a process on Windows 10 by name ?

Post by Kwai chang caine »

Works here on W10
Thanks 8)
ImageThe happiness is a road...
Not a destination
User avatar
Thunder93
Addict
Addict
Posts: 1788
Joined: Tue Mar 21, 2006 12:31 am
Location: Canada

Re: How can i Kill a process on Windows 10 by name ?

Post by Thunder93 »

tasklist could go missing. I whipped up a little something for you.

Just be-careful though. Killing process by name depending on the use could have undesirable consequences. If you killing a unique process name belonging to your package, no problem. If you targeting something else.., you could terminate the wrong target.

I could have several Notepad.exe processes running, however I might only want to target specific one. Targeting by process name isn't good approach in this case.

In the example code, I simply have it stop looking after successful kill of a target. However, like I was saying, doesn't necessarily mean I've hit my mark.

Code: Select all

If OSVersion() < #PB_OS_Windows_7
  MessageRequester("Windows OS Requirements: ", "Windows 7 and higher", #PB_MessageRequester_Ok)
  End
EndIf

;- Initialize Kernel32 Prototypes
Prototype.l EnumProcesses(*pProcessIds, cb.l, pBytesReturned.l)
Prototype.l EnumProcessModules(hProcess, lphModule.l, cb.l, lpcbNeeded.l)
Prototype.l GetModuleBaseName(hProcess, hModule.l, *lpBaseName, nSize.l)

Procedure.b Kernel32_Init()
  Shared Kernel32
  Protected Retr.b, fExt.s
  
  Kernel32 = OpenLibrary(#PB_Any, "Kernel32.dll")
  If Kernel32 <> 0
    CompilerIf #PB_Compiler_Unicode : fExt = "W" : CompilerElse : fExt = "A" : CompilerEndIf
    
    Global EnumProcesses.EnumProcesses = GetFunction(Kernel32, "K32EnumProcesses")
    Global EnumProcessModules.EnumProcessModules = GetFunction(Kernel32, "K32EnumProcessModules")
    Global GetModuleBaseName.GetModuleBaseName = GetFunction(Kernel32, "K32GetModuleBaseName"+fExt)
    Retr = 1
  EndIf
  
  ProcedureReturn Retr
EndProcedure

;- DeInitialize Kernel32 Prototypes
Procedure.b Kernel32_End()
  Shared Kernel32
  CloseLibrary(Kernel32)
EndProcedure

Procedure.l EnumProcessesSmart(nInitNumProc.l = 1024)
  ; Enumerate all running processes (independent of the number of processes running in the system)
  ; 'nInitNumProc' = initial number of processes To allocate the Array For 
  ;                 (it will be increased If there're more processes running)  
  
  Protected.l nNumProc = nInitNumProc, dwNumProcUsed, LoopSafety, ProcCount
  
  Global Dim pIDs.l(nInitNumProc) : nNumProc = nInitNumProc  
  
  Repeat   
    If EnumProcesses(@pIDs(), nNumProc * SizeOf( LONG ), @dwcbBytesNeeded.l)
      dwNumProcUsed = dwcbBytesNeeded / SizeOf(LONG)
      
      If dwNumProcUsed < nNumProc
        nNumProc = dwNumProcUsed       
        ReDim pIDs(nNumProc-1)
        ProcCount = nNumProc
        Break        
        
      Else
        ; Increase our Array size for the next iteration
        nNumProc + nInitNumProc
        ReDim pIDs(nNumProc)       
      EndIf
    EndIf
    
    LoopSafety + 1
  Until LoopSafety > 4
  
  
  If Not ProcCount
    FreeArray(pIDs()) : nNumProc = 0
  EndIf
  
  ProcedureReturn nNumProc
EndProcedure

Procedure.l KillProcName(ProcessByName.s)
  Protected.l ProcCount, Retr, State.b
  
  If Kernel32_Init()
    
    If EnumProcessesSmart(200)
      Protected hProcess, szProcessName.s = Space(#MAX_PATH)
      
      For k=1 To ArraySize(pIDs())        
        hProcess = OpenProcess_( #PROCESS_ALL_ACCESS, #False, pIDs(k))
        
        If hProcess
          If EnumProcessModules(hProcess, #Null, #Null, @cbNeeded.l)
            
            GetModuleBaseName(hProcess, #Null, @szProcessName, cbNeeded)
            
            ; find the process and kill it
            If LCase(szProcessName) = LCase(ProcessByName)
              Retr = #WAIT_OBJECT_0
              
              While Retr = #WAIT_OBJECT_0
                ; use WaitForSingleObject to make sure it's dead
                Retr = WaitForSingleObject_(hProcess, 100)
                TerminateProcess_(hProcess, 0)
              Wend
              
              State = #True
              Break
              
            EndIf
          EndIf
          
          CloseHandle_(hProcess)
        EndIf
      Next
      
      FreeArray(pIDs())
    EndIf    
    
    Kernel32_End()
  EndIf
  
  ProcedureReturn State    
EndProcedure


If KillProcName("Notepad.exe")
  Debug "Successfully Killed Notepad.exe"
EndIf
ʽʽSuccess is almost totally dependent upon drive and persistence. The extra energy required to make another effort or try another approach is the secret of winning.ʾʾ --Dennis Waitley
User avatar
skinkairewalker
Enthusiast
Enthusiast
Posts: 635
Joined: Fri Dec 04, 2015 9:26 pm

Re: How can i Kill a process on Windows 10 by name ?

Post by skinkairewalker »

Thunder93 wrote:tasklist could go missing. I whipped up a little something for you.

Just be-careful though. Killing process by name depending on the use could have undesirable consequences. If you killing a unique process name belonging to your package, no problem. If you targeting something else.., you could terminate the wrong target.

I could have several Notepad.exe processes running, however I might only want to target specific one. Targeting by process name isn't good approach in this case.

In the example code, I simply have it stop looking after successful kill of a target. However, like I was saying, doesn't necessarily mean I've hit my mark.

Code: Select all

If OSVersion() < #PB_OS_Windows_7
  MessageRequester("Windows OS Requirements: ", "Windows 7 and higher", #PB_MessageRequester_Ok)
  End
EndIf

;- Initialize Kernel32 Prototypes
Prototype.l EnumProcesses(*pProcessIds, cb.l, pBytesReturned.l)
Prototype.l EnumProcessModules(hProcess, lphModule.l, cb.l, lpcbNeeded.l)
Prototype.l GetModuleBaseName(hProcess, hModule.l, *lpBaseName, nSize.l)

Procedure.b Kernel32_Init()
  Shared Kernel32
  Protected Retr.b, fExt.s
  
  Kernel32 = OpenLibrary(#PB_Any, "Kernel32.dll")
  If Kernel32 <> 0
    CompilerIf #PB_Compiler_Unicode : fExt = "W" : CompilerElse : fExt = "A" : CompilerEndIf
    
    Global EnumProcesses.EnumProcesses = GetFunction(Kernel32, "K32EnumProcesses")
    Global EnumProcessModules.EnumProcessModules = GetFunction(Kernel32, "K32EnumProcessModules")
    Global GetModuleBaseName.GetModuleBaseName = GetFunction(Kernel32, "K32GetModuleBaseName"+fExt)
    Retr = 1
  EndIf
  
  ProcedureReturn Retr
EndProcedure

;- DeInitialize Kernel32 Prototypes
Procedure.b Kernel32_End()
  Shared Kernel32
  CloseLibrary(Kernel32)
EndProcedure

Procedure.l EnumProcessesSmart(nInitNumProc.l = 1024)
  ; Enumerate all running processes (independent of the number of processes running in the system)
  ; 'nInitNumProc' = initial number of processes To allocate the Array For 
  ;                 (it will be increased If there're more processes running)  
  
  Protected.l nNumProc = nInitNumProc, dwNumProcUsed, LoopSafety, ProcCount
  
  Global Dim pIDs.l(nInitNumProc) : nNumProc = nInitNumProc  
  
  Repeat   
    If EnumProcesses(@pIDs(), nNumProc * SizeOf( LONG ), @dwcbBytesNeeded.l)
      dwNumProcUsed = dwcbBytesNeeded / SizeOf(LONG)
      
      If dwNumProcUsed < nNumProc
        nNumProc = dwNumProcUsed       
        ReDim pIDs(nNumProc-1)
        ProcCount = nNumProc
        Break        
        
      Else
        ; Increase our Array size for the next iteration
        nNumProc + nInitNumProc
        ReDim pIDs(nNumProc)       
      EndIf
    EndIf
    
    LoopSafety + 1
  Until LoopSafety > 4
  
  
  If Not ProcCount
    FreeArray(pIDs()) : nNumProc = 0
  EndIf
  
  ProcedureReturn nNumProc
EndProcedure

Procedure.l KillProcName(ProcessByName.s)
  Protected.l ProcCount, Retr, State.b
  
  If Kernel32_Init()
    
    If EnumProcessesSmart(200)
      Protected hProcess, szProcessName.s = Space(#MAX_PATH)
      
      For k=1 To ArraySize(pIDs())        
        hProcess = OpenProcess_( #PROCESS_ALL_ACCESS, #False, pIDs(k))
        
        If hProcess
          If EnumProcessModules(hProcess, #Null, #Null, @cbNeeded.l)
            
            GetModuleBaseName(hProcess, #Null, @szProcessName, cbNeeded)
            
            ; find the process and kill it
            If LCase(szProcessName) = LCase(ProcessByName)
              Retr = #WAIT_OBJECT_0
              
              While Retr = #WAIT_OBJECT_0
                ; use WaitForSingleObject to make sure it's dead
                Retr = WaitForSingleObject_(hProcess, 100)
                TerminateProcess_(hProcess, 0)
              Wend
              
              State = #True
              Break
              
            EndIf
          EndIf
          
          CloseHandle_(hProcess)
        EndIf
      Next
      
      FreeArray(pIDs())
    EndIf    
    
    Kernel32_End()
  EndIf
  
  ProcedureReturn State    
EndProcedure


If KillProcName("Notepad.exe")
  Debug "Successfully Killed Notepad.exe"
EndIf
thanks by you answer :D
User avatar
Blue
Addict
Addict
Posts: 882
Joined: Fri Oct 06, 2006 4:41 am
Location: Canada

Re: How can i Kill a process on Windows 10 by name ?

Post by Blue »

Thunder93 wrote:

Code: Select all

Procedure.b Kernel32_Init()
  Shared Kernel32
  Protected Retr.b, fExt.s
  
  Kernel32 = OpenLibrary(#PB_Any, "Kernel32.dll")
  If Kernel32 <> 0
    CompilerIf #PB_Compiler_Unicode : fExt = "W" : CompilerElse : fExt = "A" : CompilerEndIf
    
    Global EnumProcesses.EnumProcesses = GetFunction(Kernel32, "K32EnumProcesses")
    Global EnumProcessModules.EnumProcessModules = GetFunction(Kernel32, "K32EnumProcessModules")
    Global GetModuleBaseName.GetModuleBaseName = GetFunction(Kernel32, "K32GetModuleBaseName"+fExt)
    Retr = 1
  EndIf
  
  ProcedureReturn Retr
EndProcedure
Hello Thunder93.
Excellent code. Quite what i was looking for.
Your code, however, fails if the process name contains a space.
For instance, "App123.exe" (no space) gets found and killed ;
however, "App 123.exe" (notice the space) gets overlooked; in fact, it never appears on the radar of the GetModuleBaseName() proc.
The problem appears to be in EnumProcessModules(), not in your code. Can you think of a fix ? (apart from renaming the app)

A comment : I see that you keep declaring Global variables within Procedures. Why do you that ?
Does it not defeat the very purpose of declaring variables as Global ?
to my way of looking at things, that just adds an unnecessary layer of obscurity to your code.
But you may have a very good reason for organizing your code that way. Please enlighten me.

Related comment : declaring Kernel32 as Shared without having declared it outside the Procedure previously.
It works, of course, but why do it ? It dulls the sharpness of your code.

But then again, there may be something i'm not seeing here...
"That's not a bug..." said the programmer. "it's a feature! "
"Oh! I see..." replied the blind man.
Marc56us
Addict
Addict
Posts: 1479
Joined: Sat Feb 08, 2014 3:26 pm

Re: How can i Kill a process on Windows 10 by name ?

Post by Marc56us »

Blue wrote:A comment : I see that you keep declaring Global variables within Procedures. Why do you that ?
Does it not defeat the very purpose of declaring variables as Global ?
to my way of looking at things, that just adds an unnecessary layer of obscurity to your code.
But you may have a very good reason for organizing your code that way. Please enlighten me.
I don't know about him, but it's something I've also been doing lately after thinking about it. Declaring a global variable in a procedure is a simple way to save memory. Indeed, in a large program, if the procedure does not need to be used, then the global variable will not exist. The rest of the program simply needs to test for the presence of this variable, not its content. This is especially useful for arrays.
This is another interesting subtlety that PureBasic allows (and some other compilers stupidly reject). 8)

:wink:
User avatar
Blue
Addict
Addict
Posts: 882
Joined: Fri Oct 06, 2006 4:41 am
Location: Canada

Re: How can i Kill a process on Windows 10 by name ?

Post by Blue »

Marc56us wrote:...
Indeed, in a large program, if the procedure does not need to be used, then the global variable will not exist. The rest of the program simply needs to test for the presence of this variable, not its content.
...
This is another interesting subtlety that PureBasic allows (and some other compilers stupidly reject). 8)
:wink:
Merci Marc56us.
Subtle, indeed. :shock:
But, thanks to your explanation, I see it. Makes a lot of sense. And how very smart !
I love it when PB propeller heads take the time to share little gems like that. :D
"That's not a bug..." said the programmer. "it's a feature! "
"Oh! I see..." replied the blind man.
User avatar
digital32
User
User
Posts: 23
Joined: Fri Dec 28, 2012 1:28 am

Re: How can i Kill a process on Windows 10 by name ?

Post by digital32 »

Can the "Kernel32.dll" tell me how long a process had been running. I don't need to kill a process but I do need to make sure certain process have been up and running for XX seconds before I launch other process.

Example:
User Runs (A LARGE App that takes 22 seconds to Launch)
30 Seconds Later I need to change values in my base app.
Marc56us
Addict
Addict
Posts: 1479
Joined: Sat Feb 08, 2014 3:26 pm

Re: How can i Kill a process on Windows 10 by name ?

Post by Marc56us »

digital32 wrote:Can the "Kernel32.dll" tell me how long a process had been running. I don't need to kill a process but I do need to make sure certain process have been up and running for XX seconds before I launch other process.
I don't know with Kernel32.dll, but with Tasklist (present in all windows up to XP)

All process running greater than 30 sec

Code: Select all

tasklist /FI "CPUTIME gt 00:00:30"
Sample PB code using it (no need Import)

Code: Select all

Run = RunProgram("tasklist", 
                 ~"/FI \"CPUTIME gt 00:00:30\"", 
                 "", 
                 #PB_Program_Open | #PB_Program_Read | #PB_Program_Hide)
If Run 
  While ProgramRunning(Run)
    If AvailableProgramOutput(Run)
      Debug ReadProgramString(Run)
    EndIf
  Wend
  CloseProgram(Run) 
EndIf
:wink:
User avatar
digital32
User
User
Posts: 23
Joined: Fri Dec 28, 2012 1:28 am

Re: How can i Kill a process on Windows 10 by name ?

Post by digital32 »

Marc56us, thanks for the reply. However tasklist CPUTIME shows how much time the process is using on the CPU. Not the actual running time. However this pointed me in the right direction.

I'm using your code but instead of tasklist I'm using WMIC.
This is the WMI Console.
WMI is expensive on the CPU but I want be running this option all the time. Only needed to check before a user executes another process.

RunProgram("wmic", "PROCESS GET NAME, CREATIONDATE", "", #PB_Program_Open | #PB_Program_Read | #PB_Program_Hide)

If Run
While ProgramRunning(Run)
If AvailableProgramOutput(Run)
Debug ReadProgramString(Run)
EndIf
Wend
CloseProgram(Run)
EndIf

Thanks for your help.
IdeasVacuum
Always Here
Always Here
Posts: 6425
Joined: Fri Oct 23, 2009 2:33 am
Location: Wales, UK
Contact:

Re: How can i Kill a process on Windows 10 by name ?

Post by IdeasVacuum »

Put EnableExplicit at the top of the Kill Process code ............ :)

--> SizeOf() is for use with structures Edit: LONG is some form of API structure?

If the goal of assigning Global variables within Procedures is to save memory, it is just not worth the hassle.
IdeasVacuum
If it sounds simple, you have not grasped the complexity.
Post Reply