Solved

Sending windows messages to a process

Posted on 2002-05-29
8
270 Views
Last Modified: 2013-11-20
I need to send a windows messages to a process. I have the process' handle. How could I resolve this problem?.
0
Comment
Question by:svillalba
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 12

Expert Comment

by:migel
ID: 7041836
Hi!
is your process windowed?
if so you can enumerate all toplevel windows in the system and call for each
DWORD dwProcessID;
GetWindowThreadProcessId(hWnd, &dwProcessID);

to get process ID you can use ToolhelpSnapshot and enumerate all process in the system (you get ID). Next you call OpenProcess (dwID) and compare returned handle with your needed.

after all you have window handle and can send any message to it;
for example PostMessage(hWnd...)
0
 
LVL 32

Expert Comment

by:jhance
ID: 7041861
You don't send messages to a process, you send them to a window.  Processes don't process messages, WINPROCs do.

Have your process open a window, even a hidden one.  Then send messages to the window.

If you need to somehow communicate with a process that has no windows, you need to use an alternate method.  Mailslots, network sockets, events, etc.
0
 
LVL 3

Expert Comment

by:danny_pav
ID: 7041882
RTFM about PostThreadMessage.
0
 

Author Comment

by:svillalba
ID: 7041887
I use the next code to get a handle to a process.

DWORD pids[1024], size ;

// Get pids
// ---------
if( !EnumProcesses( pids, 1024, &size ) )
   params[PARAM_ERROR] = ERR_KILL_PROC ;
else
{
//Get number of processes
// -----------------------
   DWORD num_procesos = size / sizeof( size ) ;
     
   TCHAR szProcessName[MAX_PATH] = _T("");
   HANDLE hProcess ;
   HMODULE hMod ;
   DWORD cbNeeded ;

   //Check names of processes
   // ------------------------
   for( int i = 0; i < num_procesos; i++ )
   {
      //Open process to query and terminating
      // -------------------------------------
      hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_TERMINATE, FALSE, pids[i] ) ;

      if( hProcess )
      {
         //Get the module asociated to the process
         // ---------------------------------------
         if( EnumProcessModules( hProcess, &hMod, sizeof( hMod ), &cbNeeded ) )
         {
            //Get the name of the process
            // -----------------------------
            if( GetModuleBaseName( hProcess, hMod, szProcessName, sizeof( szProcessName ) ) )
            {
               //Kill the process
               // -----------------
               if( !_tcscmp( proceso, szProcessName ) )
                  TerminateProcess( hProcess, 1 )

               break ;
            }
         }  

         CloseHandle( hProcess ) ;

...

I would like to send a WM_CLOSE message to the process instead of using TerminateProcess, but I need to get the window's handle of the process in order to do it.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 32

Expert Comment

by:jhance
ID: 7041892
>>RTFM about PostThreadMessage.

Perhaps YOU should RTFM!

1) A thread is NOT a process, it's a THREAD!
2) Not all threads have a message loop.  Only UI threads.
0
 

Author Comment

by:svillalba
ID: 7041904
I forgot to comment that the process to be terminated has a window, so I need to get the hWnd to send a message to it.
0
 
LVL 12

Accepted Solution

by:
migel earned 70 total points
ID: 7042273
Hi!
So you want just close application :-) isn`t it?
here is completely exmaple how to achieve this:

   //******************
   //Header
   //******************

   #include <windows.h>

   #define TA_FAILED 0
   #define TA_SUCCESS_CLEAN 1
   #define TA_SUCCESS_KILL 2
   #define TA_SUCCESS_16 3

   DWORD WINAPI TerminateApp( DWORD dwPID, DWORD dwTimeout ) ;
   DWORD WINAPI Terminate16App( DWORD dwPID, DWORD dwThread,
                        WORD w16Task, DWORD dwTimeout );

   //******************
   //Source
   //******************

   #include "TermApp.h"
   #include <vdmdbg.h>

   typedef struct
   {
      DWORD   dwID ;
      DWORD   dwThread ;
   } TERMINFO ;

   // Declare Callback Enum Functions.
   BOOL CALLBACK TerminateAppEnum( HWND hwnd, LPARAM lParam ) ;

   BOOL CALLBACK Terminate16AppEnum( HWND hwnd, LPARAM lParam ) ;

   /*----------------------------------------------------------------
   DWORD WINAPI TerminateApp( DWORD dwPID, DWORD dwTimeout )

   Purpose:
      Shut down a 32-Bit Process (or 16-bit process under Windows 95)

   Parameters:
      dwPID
         Process ID of the process to shut down.

      dwTimeout
         Wait time in milliseconds before shutting down the process.

   Return Value:
      TA_FAILED - If the shutdown failed.
      TA_SUCCESS_CLEAN - If the process was shutdown using WM_CLOSE.
      TA_SUCCESS_KILL - if the process was shut down with
         TerminateProcess().
      NOTE:  See header for these defines.
   ----------------------------------------------------------------*/
   DWORD WINAPI TerminateApp( DWORD dwPID, DWORD dwTimeout )
   {
      HANDLE   hProc ;
      DWORD   dwRet ;

      // If we can't open the process with PROCESS_TERMINATE rights,
      // then we give up immediately.
      hProc = OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, FALSE,
         dwPID);

      if(hProc == NULL)
      {
         return TA_FAILED ;
      }

      // TerminateAppEnum() posts WM_CLOSE to all windows whose PID
      // matches your process's.
      EnumWindows((WNDENUMPROC)TerminateAppEnum, (LPARAM) dwPID) ;

      // Wait on the handle. If it signals, great. If it times out,
      // then you kill it.
      if(WaitForSingleObject(hProc, dwTimeout)!=WAIT_OBJECT_0)
         dwRet=(TerminateProcess(hProc,0)?TA_SUCCESS_KILL:TA_FAILED);
      else
         dwRet = TA_SUCCESS_CLEAN ;

      CloseHandle(hProc) ;

      return dwRet ;
   }

   /*----------------------------------------------------------------
   DWORD WINAPI Terminate16App( DWORD dwPID, DWORD dwThread,
                        WORD w16Task, DWORD dwTimeout )

   Purpose:
      Shut down a Win16 APP.

   Parameters:
      dwPID
         Process ID of the NTVDM in which the 16-bit application is
         running.

      dwThread
         Thread ID of the thread of execution for the 16-bit
         application.

      w16Task
         16-bit task handle for the application.

      dwTimeout
         Wait time in milliseconds before shutting down the task.

   Return Value:
      If successful, returns TA_SUCCESS_16
      If unsuccessful, returns TA_FAILED.
      NOTE:  These values are defined in the header for this
      function.

   NOTE:
      You can get the Win16 task and thread ID through the
      VDMEnumTaskWOW() or the VDMEnumTaskWOWEx() functions.
   ----------------------------------------------------------------*/
   DWORD WINAPI Terminate16App( DWORD dwPID, DWORD dwThread,
                        WORD w16Task, DWORD dwTimeout )
   {
      HINSTANCE      hInstLib ;
      TERMINFO      info ;

      // You will be calling the functions through explicit linking
      // so that this code will be binary compatible across
      // Win32 platforms.
      BOOL (WINAPI *lpfVDMTerminateTaskWOW)(DWORD dwProcessId,
         WORD htask) ;

      hInstLib = LoadLibraryA( "VDMDBG.DLL" ) ;
      if( hInstLib == NULL )
         return TA_FAILED ;

      // Get procedure addresses.
      lpfVDMTerminateTaskWOW = (BOOL (WINAPI *)(DWORD, WORD ))
         GetProcAddress( hInstLib, "VDMTerminateTaskWOW" ) ;

      if( lpfVDMTerminateTaskWOW == NULL )
      {
         FreeLibrary( hInstLib ) ;
         return TA_FAILED ;
      }

      // Post a WM_CLOSE to all windows that match the ID and the
      // thread.
      info.dwID = dwPID ;
      info.dwThread = dwThread ;
      EnumWindows((WNDENUMPROC)Terminate16AppEnum, (LPARAM) &info) ;

      // Wait.
      Sleep( dwTimeout ) ;

      // Then terminate.
      lpfVDMTerminateTaskWOW(dwPID, w16Task) ;

      FreeLibrary( hInstLib ) ;
      return TA_SUCCESS_16 ;
   }

   BOOL CALLBACK TerminateAppEnum( HWND hwnd, LPARAM lParam )
   {
      DWORD dwID ;

      GetWindowThreadProcessId(hwnd, &dwID) ;

      if(dwID == (DWORD)lParam)
      {
         PostMessage(hwnd, WM_CLOSE, 0, 0) ;
      }

      return TRUE ;
   }

   BOOL CALLBACK Terminate16AppEnum( HWND hwnd, LPARAM lParam )
   {
      DWORD      dwID ;
      DWORD      dwThread ;
      TERMINFO   *termInfo ;

      termInfo = (TERMINFO *)lParam ;

      dwThread = GetWindowThreadProcessId(hwnd, &dwID) ;

      if(dwID == termInfo->dwID && termInfo->dwThread == dwThread )
      {
         PostMessage(hwnd, WM_CLOSE, 0, 0) ;
      }

      return TRUE ;
   }
0
 

Author Comment

by:svillalba
ID: 7043908
I have used TerminateAppEnum function and it works fine.
Thank you very much.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
bobThere java chalenge 45 84
Question regarding Copy/Paste 16 86
maxBlock challenge 30 100
twoTwo  challenge 35 86
In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
Introduction: Displaying information on the statusbar.   Continuing from the third article about sudoku.   Open the project in visual studio. Status bar – let’s display the timestamp there.  We need to get the timestamp from the document s…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now