Page 2 of 2 FirstFirst 12
Results 11 to 15 of 15

Thread: Close a process

  1. #11
    Administrator James's Avatar
    Join Date
    May 2010
    Location
    on the intraweb
    Posts
    3,180

    Default

    Damn me,
    You're right, and when I did that it didn't compile ha. Go figure. Anywho, I got it sorted out now, but it's glitchy. For some reason when you click the button to revert back to the original users explorer window, it loads explorer.exe then hands on a blank cmd window that I can't seem to get rid of unless I close it manually (which I would like to avoid doing). Anywho here is the application and the source:
    Code:
    // Admin2.cpp : Defines the entry point for the application.
    //
    
    #include "stdafx.h"
    #include "Admin2.h"
    #include <windows.h>
    #include <tlhelp32.h>
    #include <stdio.h>
    #include <cstdio>
    #include <iostream>
    #include <string>
    
    #define MAX_LOADSTRING 100
    #define  TOGGABLE_KEYS 10002
    #define  IDT_TIMER  WM_USER + 200
    
    // Global Variables:
    HINSTANCE hInst;                                // current instance
    TCHAR szTitle[MAX_LOADSTRING];                    // The title bar text
    TCHAR szWindowClass[MAX_LOADSTRING];            // the main window class name
    
    // Forward declarations of functions included in this code module:
    ATOM                MyRegisterClass(HINSTANCE hInstance);
    BOOL                InitInstance(HINSTANCE, int);
    LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
    LRESULT    CALLBACK    myProc(HWND, UINT, WPARAM, LPARAM);
    
    HWND hWnd = CreateWindow(WC_DIALOG,(LPCWSTR)L"", WS_VISIBLE|WS_OVERLAPPEDWINDOW, 400,100,100,80,NULL,NULL,NULL,NULL);
    HWND static_label = CreateWindow((LPCWSTR)L"Static", (LPCWSTR)L"", WS_CHILD | WS_VISIBLE, 0, 0, 200, 25, hWnd,(HMENU)-1, NULL, NULL );
    HWND myButton = CreateWindow((LPCWSTR)L"BUTTON", (LPCWSTR)L"OK", WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON, 0, 0 , 105, 50, hWnd, (HMENU)ID_BUTTON1, NULL, NULL );
    
    void CloseExplorer()
    {
        char *cmd = "C:\\Windows\\System32\\taskkill.exe -f -im explorer.exe";
        system(cmd);
    }
    
    void RunAsAdmin()
    {
        char *runa = "runas /user:%computername%\\admin C:\\Windows\\explorer.exe";
        system(runa);
    }
    
    void ExitAdmin()
    {
        HWND con = FindWindowA("ConsoleWindowClass",NULL);
    
        char *cmd2 = "C:\\Windows\\System32\\taskkill.exe -f -im explorer.exe";
        char *cmd3 = "C:\\Windows\\explorer.exe";
    
        system(cmd2);
        system(cmd3);
    
        ShowWindow(con,SW_HIDE);
        FreeConsole();
    }
    
    int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
    {
        FreeConsole();
    
    //    UNREFERENCED_PARAMETER(hPrevInstance);
    //    UNREFERENCED_PARAMETER(lpCmdLine);
        
         // TODO: Place code here.
        MSG msg;
        HACCEL hAccelTable;
    
        // Initialize global strings
        
    //    LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
        LoadString(hInstance, IDC_ADMIN2, szWindowClass, MAX_LOADSTRING);
        
        MyRegisterClass(hInstance);
        
        // Perform application initialization:
        if (!InitInstance (hInstance, nCmdShow))
        {
            return FALSE;
        }
    
        hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_ADMIN2));
    
        // Main message loop:
        while (GetMessage(&msg, NULL, 0, 0))
        {
            if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    
        return (int) msg.wParam;
    }
    
    ATOM MyRegisterClass(HINSTANCE hInstance)
    {
        WNDCLASSEX wcex;
    
        wcex.cbSize = sizeof(WNDCLASSEX);
    
        wcex.style            = CS_HREDRAW | CS_VREDRAW;
        wcex.lpfnWndProc    = WndProc;
        wcex.cbClsExtra        = 0;
        wcex.cbWndExtra        = 0;
        wcex.hInstance        = hInstance;
        wcex.hIcon            = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ADMIN2));
        wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
        wcex.hbrBackground    = (HBRUSH)(COLOR_WINDOW+1);
        wcex.lpszMenuName    = MAKEINTRESOURCE(IDC_ADMIN2);
        wcex.lpszClassName    = szWindowClass;
        wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
    
        return RegisterClassEx(&wcex);
    }
    
    BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
    {
       hInst = hInstance; // Store instance handle in our global variable
    
       SetWindowLong(hWnd, DWL_DLGPROC, (long) myProc);
    
       if (!hWnd)
       {
          return FALSE;
       }
    
       //Close the user's explorer window
       CloseExplorer();
    
       //Run a new Explorer.exe shell under admin
       RunAsAdmin();
    
       ShowWindow(hWnd, SW_MINIMIZE);
       UpdateWindow(hWnd);
    
       return TRUE;
    }
    
    LRESULT CALLBACK myProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) 
    {
        int wmId;
        int wmEvent;
        HWND con = FindWindowA("ConsoleWindowClass",NULL);
    
        switch (message) 
        {
            case WM_CLOSE:
                PostQuitMessage(0);
            break;
    
            case WM_INITDIALOG:
            {
                //** Set timers
                SetTimer(hwnd, TOGGABLE_KEYS, 1, NULL);
            }
            break;
    
            case WM_COMMAND:
            {
                wmId    = LOWORD(wParam); 
                wmEvent = HIWORD(wParam); 
    
                // Parse the menu selections:
                switch (wmId)
                {
                    case ID_BUTTON1:
                    {
                        ExitAdmin();
                        ShowWindow(con,SW_HIDE);
                        FreeConsole();
                        DestroyWindow(hwnd);
                    }
                    break;
                }
            }
            break;
    
            case WM_TIMER:
            {
                
            }
            break;
    
            //default:
            //    return DefWindowProc(hWnd, message, wParam, lParam);
        }
        return 0; 
    }
    
    LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
        int wmId, wmEvent;
        PAINTSTRUCT ps;
        HDC hdc;
    
        switch (message)
        {
            case WM_INITDIALOG:
            {
    
            }
            break;
    
            case WM_COMMAND:
            {
                wmId    = LOWORD(wParam);
                wmEvent = HIWORD(wParam);
                // Parse the menu selections:
                switch (wmId)
                {
                    case IDM_EXIT:
                        DestroyWindow(hWnd);
                    break;
    
                    default:
                        return DefWindowProc(hWnd, message, wParam, lParam);
                }
            }
            break;
    
            case WM_PAINT:
            {
                hdc = BeginPaint(hWnd, &ps);
                // TODO: Add any drawing code here...
                EndPaint(hWnd, &ps);
            }
            break;
    
            case WM_DESTROY:
            {
                PostQuitMessage(0);
            }
            break;
    
            case WM_TIMER:
            {
    
            }
    
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
        }
        return 0;
    }
    Should work with Win7, but for some reason some pc's are glitching (works fine for my Win7 x64 machine though heh).
    Attached Files Attached Files

  2. #12
    Administrator JoTo's Avatar
    Join Date
    May 2010
    Location
    www.scapp.net
    Posts
    1,953

    Default

    This approach is nice, but you should get into C# or VB.net James, makes coding life easier, especially if you have not much time. I will try to post my watchdog app once I have it ready, it covers starting stopping of processes, I think its something you want to do here.

  3. #13

    Default

    Nvm, didnt see new page.

  4. #14
    Administrator James's Avatar
    Join Date
    May 2010
    Location
    on the intraweb
    Posts
    3,180

    Default

    I realize this is an old thread, but since it is regarding a similar topic, I wanted to branch off of this.
    I have a few things I'm having trouble with, but I'll start with the first...

    Here is what I'm trying to do.
    If the process "sysprep.exe" is running, I want to safely exit out of it.
    I know I have to run it as admin (that's not a problem), the problem is, my code doesn't seem to work. It compiles fine, but I get an access denied error code when I launch it as admin which doesn't make sense.

    When I use a custom function SafeTerminateProcess to close the process, I get the access denied error as admin
    However, when I run this as admin

    char *cmd = "C:\\Windows\\System32\\taskkill.exe -f -im sysprep.exe";
    system(cmd);


    It exits properly without any error code.... Why doesn't my first method work?

    Here is my code:

    #include "stdafx.h"
    #include <Windows.h>
    #include <stdlib.h>
    #include <tchar.h>
    #include <sys/stat.h>
    #include <psapi.h>
    #include <iostream>
    #include <tlhelp32.h>


    #pragma comment(lib, "psapi.lib")


    using namespace std;


    //Check if file exists
    //If this returns true, then the file exists
    //If this returns false, file doesn't exist
    inline bool fileExists(const std::string& name)
    {
    struct stat buffer;
    return (stat(name.c_str(), &buffer) == 0);
    }


    //Check if a specific process is running
    bool IsProcessRunning(char *processName)
    {
    bool exists = false;
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);


    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);


    if (Process32First(snapshot, &entry))
    while (Process32Next(snapshot, &entry))
    if (!_stricmp(entry.szExeFile, processName))
    exists = true;


    CloseHandle(snapshot);
    return exists;
    }


    unsigned long GetProcessId(char* pszProcessName)
    {
    unsigned long dwResult = 0;


    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(hSnapshot)
    {
    PROCESSENTRY32 processEntry = {sizeof(PROCESSENTRY32)};
    if(Process32First(hSnapshot, &processEntry ))
    {
    do
    {
    if(strcmp(processEntry.szExeFile, pszProcessName) == 0)
    {
    dwResult = processEntry.th32ProcessID;
    break;
    }
    }
    while(Process32Next(hSnapshot, &processEntry));
    }


    if(hSnapshot)
    {
    CloseHandle(hSnapshot);
    hSnapshot = NULL;
    }
    }


    return dwResult;
    }


    //Safely exit out of a process
    BOOL SafeTerminateProcess(HANDLE hProcess, UINT uExitCode)
    {
    DWORD dwTID, dwCode, dwErr = 0;
    HANDLE hProcessDup = INVALID_HANDLE_VALUE;
    HANDLE hRT = NULL;
    HINSTANCE hKernel = GetModuleHandle(_T("kernel32"));


    BOOL bSuccess = FALSE;
    BOOL bDup = DuplicateHandle(GetCurrentProcess(), hProcess, GetCurrentProcess(), &hProcessDup, PROCESS_ALL_ACCESS, FALSE, 0);


    if (GetExitCodeProcess((bDup) ? hProcessDup : hProcess, &dwCode) && (dwCode == STILL_ACTIVE))
    {
    FARPROC pfnExitProc;
    pfnExitProc = GetProcAddress(hKernel, "ExitProcess");
    hRT = CreateRemoteThread((bDup) ? hProcessDup : hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pfnExitProc, (PVOID)uExitCode, 0, &dwTID);

    if (hRT == NULL)
    dwErr = GetLastError();
    }
    else
    {
    dwErr = ERROR_PROCESS_ABORTED;
    }


    if (hRT)
    {
    WaitForSingleObject((bDup) ? hProcessDup : hProcess, INFINITE);
    CloseHandle(hRT);
    bSuccess = TRUE;
    }


    if (bDup)
    CloseHandle(hProcessDup);


    if (!bSuccess)
    SetLastError(dwErr);


    return bSuccess;
    }


    bool setDebug()
    {
    HANDLE hToken;


    if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    {
    TOKEN_PRIVILEGES tp;
    LUID luid;
    TOKEN_PRIVILEGES tpPrevious;
    DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES);

    if(LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &luid))
    {
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Luid = luid;
    tp.Privileges[0].Attributes = 0;

    if(AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &tpPrevious, &cbPrevious))
    {
    tpPrevious.PrivilegeCount = 1;
    tpPrevious.Privileges[0].Luid = luid;
    tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);

    if(AdjustTokenPrivileges( hToken, FALSE, &tpPrevious, cbPrevious, NULL, NULL ))
    {
    CloseHandle(hToken);
    return true;
    }
    }
    }
    }
    CloseHandle(hToken);
    return false;
    }


    int _tmain(int argc, _TCHAR* argv[])
    {
    unsigned long dwPID1 = GetProcessId("sysprep.exe");
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ, false, dwPID1);


    if(setDebug)
    {
    if(IsProcessRunning("sysprep.exe"))
    {
    /*
    //Exit the process
    SafeTerminateProcess(hProcess,0);
    */
    char *cmd = "C:\\Windows\\System32\\taskkill.exe -f -im sysprep.exe";
    system(cmd);


    //If there is an error, output its value
    if(GetLastError != 0)
    {
    cout << "Error Code: " << GetLastError() << "\n" << endl;
    }
    }
    else
    {
    //Try to start the process manually
    ShellExecute(NULL, "open", "C:\\Windows\\System32\\sysprep\\sysprep.exe", NULL, NULL, SW_SHOWNORMAL);


    //If there is an error, output its value
    if(GetLastError != 0)
    {
    cout << "Error Code: " << GetLastError() << "\n" << endl;
    }


    }
    CloseHandle(hProcess);
    }


    system("Pause");


    return 0;
    }

  5. #15
    Administrator James's Avatar
    Join Date
    May 2010
    Location
    on the intraweb
    Posts
    3,180

    Default

    Just a quick update, I got the process to close fine using the standard TerminateProcess() function, but still nto sure why the custom one doesn't work. It's supposed to be a "cleaner" way to exit out of a process, but it doesn't seem to work.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •