Re: How to kill a single process

General Help regarding HMG, Compilation, Linking, Samples

Moderator: Rathinagiri

Post Reply
User avatar
Clip2Mania
Posts: 99
Joined: Fri Jun 13, 2014 7:16 am
Location: Belgium

How to kill a single process

Post by Clip2Mania »

Hi,

I've read this topic and this one (second one does not compile here, btw - error in "upper" ?), but by which commands can I kill a single process?

Kind Regards,
Erik
gdp
Posts: 47
Joined: Mon Jan 21, 2013 12:57 am

Re: How to kill a single process

Post by gdp »

Hi,
I Use this code for kill EXCEL process.
I hope you find it useful.

Code: Select all

Function  MAin
   Local aMatriz:= StatusExe(), i
 
       StatusExe([EXCEL.EXE], 2)  /// BORRA de memoria el excel
       
Return (Nil)
 
Function Statusexe(cExecutavel, nDerruba)
   * Exemplo postado no PCTOLEDO: Leonardo Machado, alterada por José Alves Siqueira, alterada x GDP 
   * Modificado em 29/03/2012 para minigui 3.0 x harbour por Marcelo Antonio Lázzaro Carli - malcarli@...
   * STATUSEXE()               - Verifica cuales son los executables activos, retorna array
   * STATUSEXE("TESTE.EXE", 1) - Verifica si el ejecutable esta activo, retorna .T. o .F.
   * STATUSEXE("TESTE.EXE", 2) - Cierra el ejecutable
 
   Local aNomesProcesso:={}, oScriptObj, oWmiService, oListaProcess, oProcessos, lRet:= .F.
   If nDerruba == Nil
      nDerruba:= 0
   Endif
 
	   BEGIN SEQUENCE WITH {|oErr| break( oErr )}
	       oScriptObj := CREATEOBJECT([wbemScripting.SwbemLocator])
	       oWmiService:= oScriptObj:ConnectServer()
	   RECOVER
   Return (IIF(nDerruba == 0, aNomesProcesso, lRet))
   
   END
 
   BEGIN SEQUENCE WITH {|oErr| break( oErr )}
       oListaProcess:= oWmiService:ExecQuery("select * from Win32_Process" + IIF(nDerruba == 0,""," where Name='" + cExecutavel + "'"))
   RECOVER
       Return (IIF(nDerruba == 0, aNomesProcesso, lRet))
   END
   For Each oProcessos in oListaProcess
       AADD(aNomesProcesso, oProcessos:Name())
       lRet:= .T.
       If nDerruba == 2
          oProcessos:Terminate()
       Endif
   Next
   
Return (IIF(nDerruba == 0, aNomesProcesso, lRet))
Best Regards

Gerardo Pérez
User avatar
Clip2Mania
Posts: 99
Joined: Fri Jun 13, 2014 7:16 am
Location: Belgium

Re: How to kill a single process

Post by Clip2Mania »

I will try it. Thank you!
User avatar
bpd2000
Posts: 1207
Joined: Sat Sep 10, 2011 4:07 am
Location: India

Re: How to kill a single process

Post by bpd2000 »

This may help you

Code: Select all

/* BPD2000 */
// Find running program from the windows title of running program / process, once found kill said program

#include "hmg.ch"


#define GW_HWNDFIRST 0
#define GW_HWNDLAST  1
#define GW_HWNDNEXT  2
#define GW_HWNDPREV  3
#define GW_OWNER     4
#define GW_CHILD     5


#define SW_NORMAL 1
#define WM_CLOSE         16
#define SM_CXSIZEFRAME   32


FUNCTION MAIN()
    Public hWndx
DEFINE WINDOW Win_1 ;
      ROW 0 ;
      COL 0 ;
      WIDTH 650 ;
      HEIGHT 350 ;
      TITLE "Get Handle by Search of Window's title" ;
      MAIN
      
      ON KEY ESCAPE ACTION ThisWindow.Release
          
      @ 10, 10 button bt1 CAPTION "Search"   ACTION (ShowResult(), msginfo(SearchWindow( (Win_1.tbx1.Value)),"Handle"))
      @ 10,110 button bt2 CAPTION "Show" ACTION ShowWindow( SearchWindow((Win_1.tbx1.Value))) 
      @ 10,210 button bt3 CAPTION "Hide" ACTION  HIDEWINDOW( SearchWindow((Win_1.tbx1.Value)))  
      @ 180,20 textbox tbx1 value "Find Handle" TOOLTIP "Enetr title name of running program to find handle and kill" 
      @ 160,20 LABEL Label_1 VALUE  "Enetr title name of running program to find handle and kill"  AUTOSIZE FONTCOLOR BLUE
      @ 40, 10 button bt4 CAPTION "TitleChng"   ACTION SetWindowText( SearchWindow((Win_1.tbx1.Value)), "New_Text" )
      @ 40,110 button bt5 CAPTION "Bring to Top" ACTION SETFOCUS( SearchWindow((Win_1.tbx1.Value)))
      @ 80, 10 button bt6 CAPTION "Minimize" ACTION Minimize(SearchWindow((Win_1.tbx1.Value)))
      @ 80,110 button bt7 CAPTION "Maximize" ACTION Maximize(SearchWindow((Win_1.tbx1.Value)))
      
      @ 110,10 button bt9 CAPTION "Terminate" ACTION POSTMessage(SearchWindow(Win_1.tbx1.Value), WM_CLOSE)
    
   
   END WINDOW // Win_1
   CENTER Window Win_1
   ACTIVATE Window Win_1

RETURN NIL

FUNCTION ShowResult()
 LOCAL hWnd := SearchWindow( (Win_1.tbx1.Value))
 hWndx := hWnd
    IF !EMPTY( hWnd )
        msginfo( GETWINDOWTEXT( hWnd ),"Handle: " + hb_ntos(hWnd)+ space(10))
      ELSE
        msginfo( "Window title not found")
    ENDIF
Return Nil

FUNCTION SearchWindow( cTitle )

    LOCAL hWnd := GETWINDOW( GETDESKTOPWINDOW(), GW_CHILD )

    WHILE hWnd != 0
            IF UPPER( cTitle ) $ UPPER( GETWINDOWTEXT( hWnd ) )
           RETURN hWnd
        ENDIF

        hWnd = GETWINDOW( hWnd, GW_HWNDNEXT )
    ENDDO

    RETURN NIL

Last edited by bpd2000 on Mon Feb 24, 2020 12:32 pm, edited 1 time in total.
BPD
Convert Dream into Reality through HMG
User avatar
srvet_claudio
Posts: 2193
Joined: Thu Feb 25, 2010 8:43 pm
Location: Uruguay
Contact:

Re: How to kill a single process

Post by srvet_claudio »

This example I post in another topic but cant find it, so I repeat the code here:

Code: Select all


// By Dr. Claudio Soto (April 2014)

*****************************************************************************************************
* Attention: to detect processes 32 and 64 bits you should compiling with HMG-64 bits (Build64.bat)
*****************************************************************************************************

// The double click allow you terminate the process

#include "hmg.ch"

Function Main

#define WIN32_PREFIX "*32"

aRows := {}
aProcessesID := EnumProcessesID () 

   FOR i = 1 TO HMG_LEN (aProcessesID)
      nID := aProcessesID [i]
      c32 := IF (IsWow64Process(nID) ,WIN32_PREFIX,"")
      cName := GetProcessName(nID)
      cNameFull := GetProcessFullName(nID)
      IF .NOT. EMPTY (cNameFull)
         AADD ( aRows, {HB_NTOS(nID), cName+c32, cNameFull} )
      ENDIF
   NEXT
   ASORT ( aRows, , , {|x,y| HMG_UPPER(x[2]) < HMG_UPPER(y[2]) } )

   DEFINE WINDOW Form_1 ;
      AT 0,0 ;
      WIDTH 800 ;
      HEIGHT 550 ;
      BACKCOLOR TEAL;
      TITLE 'EnumProcesses' ;
      MAIN 

      fColor := { || IF (GetCurrentProcessID() == VAL ( Form_1.Grid_1.CellEx (This.CellRowIndex, 1) ), AQUA, IF (This.CellColIndex == 2 .AND. HB_URIGHT (This.CellValue,HMG_LEN (WIN32_PREFIX)) == WIN32_PREFIX, RED, BLUE)) }
      bColor := { || IF (GetCurrentProcessID() == VAL ( Form_1.Grid_1.CellEx (This.CellRowIndex, 1) ), GRAY, NIL) }
      
      @ 30,10 GRID Grid_1 ;
         WIDTH 760 ;
         HEIGHT 450 ;
         BACKCOLOR {192,192,192};
         FONT "Courier New" SIZE 12;
         HEADERS {'ID','Name','Full Name'} ;
         WIDTHS {100,0,0};
         ITEMS aRows ;
         VALUE {1,1} ;
         ON DBLCLICK PROC_Terminate_Process();
         DYNAMICFORECOLOR {fColor, fColor, fColor};
         DYNAMICBACKCOLOR {bColor, bColor, bColor};
         JUSTIFY {GRID_JTFY_RIGHT, NIL, NIL};
         CELLNAVIGATION

         Form_1.Grid_1.ColumnWIDTH (2) := GRID_WIDTH_AUTOSIZE
         Form_1.Grid_1.ColumnWIDTH (3) := GRID_WIDTH_AUTOSIZE

         Form_1.Grid_1.ColumnDYNAMICFONT (1) := {|| FUNC_ColumnDYNAMIC_FONT() }
         Form_1.Grid_1.ColumnDYNAMICFONT (2) := {|| FUNC_ColumnDYNAMIC_FONT() }
         Form_1.Grid_1.ColumnDYNAMICFONT (3) := {|| FUNC_ColumnDYNAMIC_FONT() }

   END WINDOW

   CENTER WINDOW Form_1

   ACTIVATE WINDOW Form_1

Return


PROCEDURE PROC_Terminate_Process
LOCAL nID := VAL (Form_1.Grid_1.CellEx (Form_1.Grid_1.CellRowFocused, 1))
   IF MsgYesNo ({nID, " : ", Form_1.Grid_1.CellEx (Form_1.Grid_1.CellRowFocused, 2)}, "Terminate Process") == .T.
      TerminateProcess (nID)
   ENDIF
RETURN


FUNCTION FUNC_ColumnDYNAMIC_FONT
LOCAL aFont := NIL

   IF GetCurrentProcessID() == VAL ( Form_1.Grid_1.CellEx (This.CellRowIndex, 1) )
      DO CASE
         CASE This.CellColIndex == 1
            aFont := ARRAY FONT "Courier New" SIZE 14 BOLD
            
         CASE This.CellColIndex == 2
            aFont := ARRAY FONT "Calibri" SIZE 14 BOLD ITALIC
            
         CASE This.CellColIndex == 3
            aFont := ARRAY FONT "Comic Sans MS" SIZE 14 BOLD
            
      ENDCASE
   ENDIF
RETURN aFont
PS: Only for info:

Code: Select all

      - GetCurrentProcessId() --> return nProcessID
      - EnumProcessesID () ---> return array { nProcessID1, nProcessID2, ... }
      - GetProcessName ( [ nProcessID ] ) --> return cProcessName
      - GetProcessFullName ( [ nProcessID ] ) --> return cProcessFullName
      - GetProcessMemoryInfo ( [ ProcessID ] )  --> return array with 9 numbers
      - GetWindowThreadProcessId (hWnd, @nThread, @nProcessID)
      - IsWow64Process ( [ nProcessID ] ) --> return lBoolean
         - return TRUE  if a 32-bit application is running under 64-bit Windows (WOW64)
         - return FALSE if a 32-bit application is running under 32-bit Windows
         - return FALSE if a 64-bit application is running under 64-bit Windows
         - WOW64 is the x86 emulator that allows 32-bit Windows-based applications to running on 64-bit Windows
Best regards.
Dr. Claudio Soto
(from Uruguay)
http://srvet.blogspot.com
User avatar
danielmaximiliano
Posts: 2607
Joined: Fri Apr 09, 2010 4:53 pm
Location: Argentina
Contact:

Re: How to kill a single process

Post by danielmaximiliano »

Gracias por el codigo Claudio....
*´¨)
¸.·´¸.·*´¨) ¸.·*¨)
(¸.·´. (¸.·` *
.·`. Harbour/HMG : It's magic !
(¸.·``··*

Saludos / Regards
DaNiElMaXiMiLiAnO

Whatsapp. := +54901169026142
Telegram Name := DaNiElMaXiMiLiAnO
User avatar
Clip2Mania
Posts: 99
Joined: Fri Jun 13, 2014 7:16 am
Location: Belgium

Re: How to kill a single process

Post by Clip2Mania »

Thanks all! Learned a lot :-)
User avatar
Pablo César
Posts: 4059
Joined: Wed Sep 08, 2010 1:18 pm
Location: Curitiba - Brasil

How to kill a single process

Post by Pablo César »

bpd2000 wrote: Fri Jan 23, 2015 2:24 pm This may help you

Code: Select all

/* BPD2000 */
// Find running program from the windows title of running program / process, once found kill said program

#include "hmg.ch"


#define GW_HWNDFIRST 0
#define GW_HWNDLAST  1
#define GW_HWNDNEXT  2
#define GW_HWNDPREV  3
#define GW_OWNER     4
#define GW_CHILD     5


#define SW_NORMAL 1


FUNCTION MAIN()
    Public hWndx
DEFINE WINDOW Win_1 ;
      ROW 0 ;
      COL 0 ;
      WIDTH 650 ;
      HEIGHT 350 ;
      TITLE "Get Handle by Search of Window's title" ;
      MAIN
      
      ON KEY ESCAPE ACTION ThisWindow.Release
          
      @ 10, 10 button bt1 CAPTION "Search"   ACTION (ShowResult(), msginfo(SearchWindow( (Win_1.tbx1.Value)),"Handle"))
      @ 10,110 button bt2 CAPTION "Show" ACTION ShowWindow( SearchWindow((Win_1.tbx1.Value))) 
      @ 10,210 button bt3 CAPTION "Hide" ACTION  HIDEWINDOW( SearchWindow((Win_1.tbx1.Value)))  
      @ 180,20 textbox tbx1 value "Find Handle" TOOLTIP "Enetr title name of running program to find handle and kill" 
      @ 160,20 LABEL Label_1 VALUE  "Enetr title name of running program to find handle and kill"  AUTOSIZE FONTCOLOR BLUE
      @ 40, 10 button bt4 CAPTION "TitleChng"   ACTION SetWindowText( SearchWindow((Win_1.tbx1.Value)), "New_Text" )
      @ 40,110 button bt5 CAPTION "Bring to Top" ACTION SETFOCUS( SearchWindow((Win_1.tbx1.Value)))
      @ 80, 10 button bt6 CAPTION "Minimize" ACTION Minimize(SearchWindow((Win_1.tbx1.Value)))
      @ 80,110 button bt7 CAPTION "Maximize" ACTION Maximize(SearchWindow((Win_1.tbx1.Value)))
      
      @ 110,10 button bt9 CAPTION "Terminate" ACTION POSTMessage(SearchWindow(Win_1.tbx1.Value), WM_CLOSE)
   
   END WINDOW // Win_1
   CENTER Window Win_1
   ACTIVATE Window Win_1

RETURN NIL

FUNCTION ShowResult()
 LOCAL hWnd := SearchWindow( (Win_1.tbx1.Value))
 hWndx := hWnd
    IF !EMPTY( hWnd )
        msginfo( GETWINDOWTEXT( hWnd ),"Handle: " + hb_ntos(hWnd)+ space(10))
      ELSE
        msginfo( "Window title not found")
    ENDIF
Return Nil

FUNCTION SearchWindow( cTitle )

    LOCAL hWnd := GETWINDOW( GETDESKTOPWINDOW(), GW_CHILD )

    WHILE hWnd != 0
            IF UPPER( cTitle ) $ UPPER( GETWINDOWTEXT( hWnd ) )
           RETURN hWnd
        ENDIF

        hWnd = GETWINDOW( hWnd, GW_HWNDNEXT )
    ENDDO

    RETURN NIL

Hi Dave,

A long time passed and no one noticed the jewel we have left behind. :oops:

Your example has served me very well. :P
 
Screen70.png
Screen70.png (87.07 KiB) Viewed 6224 times
 
I made some adaptations to my need and would like to share it with all of you.
One of the advantages is getting all windows that have the same title returning in ARRAY.
 
Kill_Process.rar
Source files
(2.6 KiB) Downloaded 356 times
 
I needed to detect the IDE window with the project name.

I just did not get more precise because the old IDEs do not have the name of the project on the main screen, but in the "Project Browser" screen yes. However names like Demo2.hbp there may be in duplicity open... :|

 
Thank you very much Dave for your contribution. :)
HMGing a better world
"Matter tells space how to curve, space tells matter how to move."
Albert Einstein
kristalist
Posts: 21
Joined: Thu Apr 23, 2015 2:30 pm
DBs Used: DBF

Re: Re: How to kill a single process

Post by kristalist »

Hi, Pablo!
Useful example. But typo in demo2.prg:SelectOne function -

Code: Select all

Function SelectOne(ahWnd)
LOCAL hwd, i, nOpt, aItems:= {}, nLen := Len(ahWnd)

If nLen = 1
   //hwd := ahWnd[1,2]
   hwd := ahWnd[1,1]
Else
   For i=1 To nLen
       //AADD(aItems,"Handle: "+AllTrim(Str(ahWnd[i,2])))
       AADD(aItems,"Handle: "+AllTrim(Str(ahWnd[i,1])))
   Next
   nOpt := OptionBox("Please select one of these","",aItems)
   If nOpt > 0
      //hwd := ahWnd[nOpt,2]
      hwd := ahWnd[nOpt,1]
   Endif
Endif
Return hwd
Post Reply