How to close a process on a task manager

i want to make a simple dialog base program that have a single button, and that button will close a specific program or process that is running. to be specific i want to close the spooler.exe

a simple code will do.


thank you very much.
LVL 1
haroldxiousAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mahesh1402Commented:
You may refer this with src code 'Advanced Task Manager in MFC'

http://www.codeproject.com/system/advancedtaskmanager.asp <== This article demonstrates how to create a Task Manager in MFC which lists all the processes running in the system along with their process details and version information and  allows you to kill selected task.

MAHESH
0
haroldxiousAuthor Commented:
hello mahesh, ive tried to download the source of advanced task manager then ive tried to run it, but it cannot delete the spoolsv.exe.

im using win xp. try it.

open the control pannel then in management tool go to service then to Print Spooler then click the play button. the spoolsv.exe will be seen in the process window. then ive tried to end task using the advanced task manager but it doesent work. pls help.


thank you very much
0
ZoppoCommented:
Hi haroldxious,

I guess you don't have enough rights to kill the service - can you kill the service with Window's TaskManager?

BTW, I think the better way to stop a service (except maybe when the service hangs) would be to terminate it the same way as if you would press the 'Stop' button in service-control-panel.

You can do this via the Service Control Manager - see MSDN about functions OpenSCManager, OpenService and ControlService.

Hope that helps,

ZOPPO
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

haroldxiousAuthor Commented:
yes i can kill it in the task manager. so im thinkin why i cant kill it on the advanced task manager program. ill try the OpenSCManager. If you have a code snippet to do this it is very much appreciated.
0
mahesh1402Commented:
You may also try by killing a process by name with help of following src :

http://www.codeproject.com/threads/killprocess.asp <==

MAHESH
0
ZoppoCommented:
Hi,

I tested this code, works for me, but I'm not sure how's about user rights, I work as local administrator ...

-----------------------------------
#include <windows.h>
#include <iostream>

int main(int argc, char* argv[])
{
      SC_HANDLE hServiceManager = OpenSCManager( NULL, NULL, SC_MANAGER_CONNECT );

      if ( NULL == hServiceManager )
      {
            std::cout << "Error opening SC-Manager; error code: " << GetLastError() << std::endl;
            return -1;
      }

      SC_HANDLE hService = OpenService( hServiceManager, "Spooler", SERVICE_STOP | SERVICE_QUERY_STATUS );

      if ( NULL == hService )
      {
            std::cout << "Error opening Spooler-service; error code: " << GetLastError() << std::endl;
            return -1;
      }

      SERVICE_STATUS ss;

      if ( FALSE == QueryServiceStatus( hService, &ss ) )
      {
            std::cout << "Error querying Spooler-service status; error code: " << GetLastError() << std::endl;
            return -1;
      }

      if ( ss.dwCurrentState == SERVICE_STOPPED )
      {
            std::cout << "Error: Spooler-service not running!" << std::endl;
            return -1;
      }
      else if ( ss.dwCurrentState == SERVICE_STOP_PENDING )
      {
            std::cout << "Error: Spooler-service is stopping!" << std::endl;
            return -1;
      }

      if ( FALSE == ControlService( hService, SERVICE_CONTROL_STOP, &ss ) )
      {
            std::cout << "Error sending STOP-message to  Spooler-service; error code: " << GetLastError() << std::endl;
            return -1;
      }

      return 0;
}
---------------------------------------

hope that helps,

ZOPPO
0
DanRollinsCommented:
And don't forget the simple way:  Execute this at the commandline:

    NET STOP SPOOLER

Make a batch file with those three words and put an icon link to it on your desktop and you are just a double-click away from stopping the spooler andy time you want.

-- Dan
0
mxjijoCommented:

As Zoppo mentioned, you need privilage to kill.
Call the following function once at the entry of your application to become a licensed :) killer
I would recomment to use the remote thread method to kill other apps, rather than using TerminateProcess()
good luck

BOOL GrabKillerPrivilage()
{
    TOKEN_PRIVILEGES Priv, PrivOld;
    DWORD cbPriv = sizeof(PrivOld);
    HANDLE hToken;
     DWORD  dwError;

    // get current thread token
    if (!OpenThreadToken(GetCurrentThread(),
                         TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                         FALSE, &hToken))
    {
        if (GetLastError() != ERROR_NO_TOKEN)
            return FALSE;
        // revert to the process token, if not impersonating
        if (!OpenProcessToken(GetCurrentProcess(),
                              TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                              &hToken))
            return FALSE;
    }

    Priv.PrivilegeCount                    = 1;
    Priv.Privileges[0].Attributes     = SE_PRIVILEGE_ENABLED;
    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Priv.Privileges[0].Luid);

    // try to enable the privilege
    if (!AdjustTokenPrivileges(hToken,
                                        FALSE,
                                        &Priv,
                                        sizeof(Priv),
                                        &PrivOld,
                                        &cbPriv))
    {
        dwError = GetLastError();
        CloseHandle(hToken);
        return SetLastError(dwError), FALSE;
    }

    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
    {
        // the SE_DEBUG_NAME privilege is not in the caller's token
        CloseHandle(hToken);
        return SetLastError(ERROR_ACCESS_DENIED), FALSE;
    }

     return TRUE;
}
0
haroldxiousAuthor Commented:
how will i end the explorer.exe and spoolsv.exe in the task manager.

i will be having a button in my application dialog that serves as an end task button. then when you press it it will automatically endtask the explorer.exe and spoolsv.exe.

please help.

thank you very much.
0
mxjijoCommented:

Sorry abt the code alignment


#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "psapi.h"


BOOL GrabKillerPrivilage()
{
    TOKEN_PRIVILEGES Priv, PrivOld;
    DWORD cbPriv = sizeof(PrivOld);
    HANDLE hToken;
     DWORD  dwError;

    // get current thread token
    if (!OpenThreadToken(GetCurrentThread(),
                         TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                         FALSE, &hToken))
    {
        if (GetLastError() != ERROR_NO_TOKEN)
            return FALSE;
        // revert to the process token, if not impersonating
        if (!OpenProcessToken(GetCurrentProcess(),
                              TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                              &hToken))
            return FALSE;
    }

    Priv.PrivilegeCount                    = 1;
    Priv.Privileges[0].Attributes     = SE_PRIVILEGE_ENABLED;
    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Priv.Privileges[0].Luid);

    // try to enable the privilege
    if (!AdjustTokenPrivileges(hToken,
                                        FALSE,
                                        &Priv,
                                        sizeof(Priv),
                                        &PrivOld,
                                        &cbPriv))
    {
        dwError = GetLastError();
        CloseHandle(hToken);
        return SetLastError(dwError), FALSE;
    }

    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
    {
        // the SE_DEBUG_NAME privilege is not in the caller's token
        CloseHandle(hToken);
        return SetLastError(ERROR_ACCESS_DENIED), FALSE;
    }

     return TRUE;
}

char* getProcessName(HANDLE hProcess)
{
    TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
    if (NULL != hProcess )
    {
        HMODULE hMod;
        DWORD cbNeeded;

        if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
             &cbNeeded) )
        {
            GetModuleBaseName( hProcess, hMod, szProcessName, MAX_PATH);
                  return strdup(szProcessName);            
        }
    }
      return NULL;
}

HANDLE openProcessToKill(char* procNameIn, DWORD* pidList, int pidCount){
      for (int i=0; i<pidCount; i++){
            HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD |
                                          PROCESS_QUERY_INFORMATION |
                                          PROCESS_VM_OPERATION |
                                          PROCESS_SET_QUOTA |
                                          PROCESS_TERMINATE |
                                          PROCESS_VM_WRITE |
                                          PROCESS_VM_READ,
                                          FALSE,
                                          pidList[i]);                                          
            
            if (hProcess){
                  char* thisProcName = getProcessName(hProcess);
                // FIXME free thisProcName after processing
                  if (thisProcName){
                        if (_stricmp(thisProcName, procNameIn) == 0){
                              _tprintf( TEXT("Targetting %s (PID=%d)\n"),  thisProcName, pidList[i]);
                              return hProcess;
                        }else{
                              CloseHandle(hProcess);
                        }
                  }
            }else{
                  _tprintf( TEXT("Cannot open PID %d\n"),  pidList[i]);
            }
      }
      return NULL;
}

void killProcess(HANDLE killableProcHandle){
      // TerminateProcess() works as well.
      DWORD id;
      CreateRemoteThread(killableProcHandle,
                                    NULL,
                                    0,
                                    (LPTHREAD_START_ROUTINE)ExitProcess,
                                    0,
                                    0,
                                    &id);
}

void main(int argc, char* argv[])
{
    // Get the list of process identifiers.
      if (argv[1]){

            DWORD aProcesses[1024], cbNeeded;
            GrabKillerPrivilage();

            if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){
                        return;
            }
            HANDLE hProcessToKill = openProcessToKill(argv[1], aProcesses, cbNeeded/sizeof(DWORD));
            if (hProcessToKill){
                  killProcess(hProcessToKill);
                  _tprintf( TEXT("\nTarget down!!\n\n"));
            }
      }else{
            _tprintf( TEXT("Usage: kill {processname}\n"));
      }
}
0
haroldxiousAuthor Commented:
hi mxjijo, ur code is for win32 console application, im doing a dialog base application. i want that if you click a button it will kill the process, how will i parse your code to that.


many thanx
0
mxjijoCommented:

Make a callable function out of main()

something like...

void
killProcessByName(char* procName) {
    DWORD aProcesses[1024], cbNeeded;
    GrabKillerPrivilage();

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){
        return;
    }
    HANDLE hProcessToKill = openProcessToKill(procName, aProcesses, cbNeeded/sizeof(DWORD));
    if (hProcessToKill){
        killProcess(hProcessToKill);
     }
}

Call the above function from you OnXxxClick();

that wud do.

Ps: please handle errors - i'm a lazy programmer

good luck.
0
haroldxiousAuthor Commented:
thanx mxjijo but i cant compile the code, the errors are:
 EnumProcessModules, GetModuleBaseName and EnumProcesses are undeclared identifiers.

can i use this in mfc dialog base app? i know that this are SDK platforms.

and by the way i didnt put #include "psapi.h" coz unidentified.

0
mahesh1402Commented:
>>ive tried to download the source of advanced task manager then ive tried to run it, but it cannot delete the spoolsv.exe.

To kill Service Process like spoolsv.exe in WMI there is StopService Method of the Win32_Service Class.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/stopservice_method_in_class_win32_service.asp

MAHESH
0
haroldxiousAuthor Commented:
thanx mahesh, but how about killing the explorer.exe?
ive used the code of mxjijo but some errors occured...
0
mxjijoCommented:
>> EnumProcessModules, GetModuleBaseName and EnumProcesses are undeclared identifiers.
>> and by the way i didnt put #include "psapi.h" coz unidentified.

   If you have platform SDK you can use #include <psapi.h> and add [platform SDK]/include to the lookup path.
If you don't have platform SDK, you have to define function pointers to those functions as follows

// PSAPI definitions
typedef BOOL  (WINAPI *pfn_EnumProcesses)(DWORD*, DWORD, DWORD*);
typedef BOOL  (WINAPI *pfn_EnumProcessModules) (HANDLE, HMODULE*, DWORD, LPDWORD);
typedef DWORD (WINAPI *pfn_GetModuleFileNameEx) (HANDLE, HMODULE, LPTSTR, DWORD);

// now define function pointers
pfn_EnumProcesses            EnumProcesses;
pfn_EnumProcessModules      EnumProcessModules;
pfn_GetModuleFileNameEx      GetModuleFileNameEx;      

// then load those functions from psapi dll as follows

HMODULE m_hPsApidll = LoadLibrary("PsAPI.DLL");

if (m_hPsApidll)
{
  EnumProcesses = (pfn_EnumProcesses)GetProcAddress(m_hPsApidll, "EnumProcesses");
  EnumProcessModules = (pfn_EnumProcessModules)GetProcAddress(m_hPsApidll, "EnumProcessModules");
  GetModuleFileNameEx = (pfn_GetModuleFileNameEx)GetProcAddress(m_hPsApidll, "GetModuleFileNameExA");
}



FYI:
We have given you every single details of the implementation.
Poeple usually don't help you out this deep.
I have seen you posting the same question again - don't know why
Please note that there is no one line code to do what want to do :)

bye...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
haroldxiousAuthor Commented:
hello, im sorry guys if im such a noob. its my first time to use mfc.
im very very sorry
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Fonts Typography

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.