HWND GetProcessWindow( IN DWORD dwProcessId )
{
        // Enumerating all windows with given (EnumProc) condition
        ENUMINFO info;
        info.dwProcessID = dwProcessId;
        info.hwnd = NULL;
        
        ::EnumWindows(EnumProc, (LPARAM)&info);
        
        return info.hwnd;
}

tstring GetModuleFileName( HMODULE _Mod )
{
        // This function retrieves the file name of the module
        vectorTCHAR filename(MAX_PATH);
        if( !::GetModuleFileName( _Mod, &filename[0], MAX_PATH ) )
        return tstring();
        tstring fullpath( &filename[0] );
        fullpath.erase( 0, fullpath.find_last_of(_T("\\"))+1 );
        return fullpath;
}

void SetWndForeground()
{
        std::vector<DWORD> aProcesses(1024);
        DWORD cbNeeded;
        if ( !::EnumProcesses( &aProcesses[0], static_cast<DWORD>(aProcesses.capacity()), &cbNeeded ) )
        return;
        
        HMODULE hMod;
        DWORD ProcID = 0;
        tstring strCurrentModuleFileName( GetModuleFileName(NULL) );
        for( size_t i = 0, size = cbNeeded/sizeof(DWORD); i < size; ++i )
        {
                // Get a handle to the process.
                HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, aProcesses[i] );
                if( !hProcess )
                continue;
                if( ::EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded) )
                {
                        vectorTCHAR szProcessName(1024);
                        ::GetModuleBaseName( hProcess, hMod, &szProcessName[0], static_cast<DWORD>(szProcessName.capacity()) );
                        tstring module_name( &szProcessName[0] );
                        if( module_name == strCurrentModuleFileName )
                        {
                                DWORD pid = ::GetProcessId(hProcess);
                                if( pid != ::GetCurrentProcessId() )
                                ProcID = pid;
                        }
                }
                CloseHandle(hProcess);
        }
        
        HWND hwnd = GetProcessWindow( ProcID );
        if( hwnd != NULL )
        {
                ::ShowWindow(hwnd, SW_RESTORE);
                ::SetForegroundWindow(hwnd);
        }
}

-- AnarManafov - 30 Oct 2006
Topic revision: r1 - 2006-10-30, AnarManafov
 
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding GSI Wiki? Send feedback
Imprint (in German)
Privacy Policy (in German)