using sendmessage to send wm_close to another process

24,134

Solution 1

Are you sure that the window you are finding is the correct one? You can check easily with Spy++. Moreover, when searching for a window, I think it's better to use EnumWindows. I'm not sure your method is correct.

Solution 2

I would attempt to close a (Process with) Window(s) in the following order:

  1. WM_CLOSE

  2. WM_QUIT

  3. WM_DESTROY

  4. TerminateProcess().

Just my take as I am handling (disabling) WM_CLOSE for a Window and having difficulty distinguishing between User Close and close messages send by another master task. WM_QUIT seems to resolve my problem without using a custom WM_APP_CLOSE of my own. TerminateProcess is very much a last resort unclean exit to be avoided at all costs (it may leave handles (e.g. COM etc) and memory etc unfreed).

Share:
24,134
rplusg
Author by

rplusg

"Pro"grammer with lots of interest and experience in OS(Windows), storage, networking. And strongly believes c++ is the fastest. Currently working on C++\VC++ on Windows7, SilverLight\C# on WindowsPhone7, WindowsPhone8, Windows RT

Updated on October 26, 2020

Comments

  • rplusg
    rplusg over 3 years

    I want to send wm_close to another process, with which i want end that process safely.

    int _tmain(int argc, _TCHAR* argv[])
    {
    
        DWORD SetOfPID;
        SetOfPID = GetProcId(_T("abc.exe"));  //this will return pid
        HANDLE h = OpenProcess(PROCESS_ALL_ACCESS,false, SetOfPID);
    
        HWND hwnd = ::GetTopWindow(NULL);
        while(hwnd)
        {
            DWORD pid;
            DWORD dwThreadId = ::GetWindowThreadProcessId(hwnd, &pid);
             if(pid == SetOfPID)
             {    
                  break;
             }
             hwnd = ::GetNextWindow(hwnd, GW_HWNDNEXT);
        }
        //DestroyWindow(hwnd);
        bool temp = IsWindow(hwnd); **//this gives true**
        LRESULT res = ::SendMessage(hwnd, WM_CLOSE, NULL, NULL);
        DWORD err = GetLastError(); **//this gives 6**
        CloseHandle(hwnd);
        CloseHandle(h);
        return 0;
    }
    

    this piece of code looks good, but the target process doesn't terminate, can somebody help me?

  • rplusg
    rplusg about 13 years
    WM_DESTROY and WM_NCDESTROY also doesn't work. DestroyWindow() also returns false.
  • rplusg
    rplusg about 13 years
    IsWindow() returns true, doesn't it mean i've a valid window?
  • David Heffernan
    David Heffernan about 13 years
    WM_DESTROY and WM_NCDESTROY can't work, they are notifications.
  • pagra
    pagra about 13 years
    @rplusg: IsWindow tells you it is a valid window handle, not more. It can be that the application has got several top level windows, maybe not visible. And you may not close the right one.
  • rplusg
    rplusg about 13 years
    even i'm not sure what is the problem, but enumwindows has given my desired results. Thanks patriiice, marking your answer as final.