SetForeGroundWindow Error in Vista RRS feed

  • Question


    Hi All,

      We have a old VB activex application which will be triggered from another application. This activex application is trying to do setforegroundwindow and we are getting error in VISTA alone, it is working fine NT 2000


      We tried attaching to thread and bring it to the front, it didnt work. We tried showwindow, activewindow and even Me.Show none of them worked....


      any idea on this. it is really urgent...


    - Mani

    Monday, October 20, 2008 7:14 PM

All replies

  • I don't know if you've figured it out, but I just ran into this issue and came up with a fairly good workaround:

    Under Vista, instead of using SetForegroundWindow which doesn't work, do the following:

    SetWindowPos(WndHandle,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE OR SWP_NOSIZE);

    The first one actually grabs the focus but if you have SWP_SHOWWINDOW in its flags then the window is shown as topmost and you can't make it NOT Topmost.  If, however, you don't have SWP_SHOWWINDOW in its flags then the second one actually shows it while making it NOT Topmost.

    Hope that makes sense and helps!
    • Proposed as answer by MrBytePlayer Friday, December 19, 2008 9:13 AM
    Friday, December 19, 2008 9:12 AM
  • i have tried the same thing, no joy.  i am looking for the ability to push focus to a window in another application, similar to alt-tabbing.  but i also need for it to be QUICK (<20-30ms).  my goal is to push a click to a window that needs focus before processing it.  if i could trick the window into thinking it never lost focus, that's another option (but i cannot change the winproc associated with the external application from within my application)

    any suggestions would be most welcome.

    here are a few of the attempts:

    // doesn't work at all
    void push_focus( HWND hNew )
      SetWindowPos(hNew,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE);
    } // :: push_focus

    // works, but is slow.  about 600-800ms is what i am seeing
    void push_focus( HWND hNew )
        DWORD remoteThreadId = GetWindowThreadProcessId(hNew, NULL);
        DWORD currentThreadId = GetCurrentThreadId();

        if (remoteThreadId == currentThreadId)
          return ;

        if (AttachThreadInput(remoteThreadId, currentThreadId, TRUE))
          ::SetForegroundWindow( hNew ) ;
          ::SetFocus( hNew ) ;
          ::SetWindowPos( hNew, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_ASYNCWINDOWPOS ) ;
          ::BringWindowToTop( hNew ) ;

          AttachThreadInput(remoteThreadId, currentThreadId, FALSE);
    } // :: push_focus

    target platform:  winxp, vista, vista64, and win7

    Sunday, April 19, 2009 7:54 PM