No announcement yet.

Set another window ontop & with focus

  • Filter
  • Time
  • Show
Clear All
new posts

  • Set another window ontop & with focus

    I've got an app that runs uniquely (i.e. one instance executing).

    If another EXE is started, it detects the 1st, sends it some data (via WM_COPYDATA), issues a SetFocus for the running window and then terminates itself.

    All of this is working except the original window does not seem to be given the focus (i.e. its not on top, KB activity goes to another window etc.)

    SetFocus returns with no error (0). The hWnd param must be correct as it was just used in the successful WM_COPYDATA function.

    I've searched but not found anything related, why doesn't SetFocus seem to be working? Or is SetFocus the wrong API to call?


  • #2
    >I've searched but not found anything related

    How hard did you search? I found this under, of all things, 'SetFocus':
    If the function succeeds, the return value is the handle to the window that previously had the keyboard focus. If the hWnd parameter is invalid or the window is not attached to the calling thread's message queue, the return value is NULL. To get extended error information, call GetLastError
    You can test for the success/failure of SetFocus and getting the error when it fails.

    You also can try AttachThreadInput to attach to your program's message queue and issue a SetFocus call.

    Michael Mattias
    Tal Systems (retired)
    Port Washington WI USA
    [email protected]


    • #3
      Hi Michael,

      Well I searched these forums every which way, since I'd much rather find the answer here rather than try to decode MSDN stuff, I just don't seem to be able to get usable answers there. It leans too heavily on nitty-gritty syntax questions rather than useful 'how to' stuff. Maybe its just me.

      However, using your hint, I found some stuff on Dr. Dobbs and was able to add the following code which seems to work just fine.

      Many thanks for the pointer (and the kick in the a** to search better)

         MyThread = GetWindowThreadProcessId(hWndMe, 0)   
         OtherThread = GetWindowThreadProcessId(hWndHim, 0)
         AttachThreadInput(MyThread, OtherThread, %TRUE)
         AttachThreadInput(MyThread, OtherThread, %FALSE)
         IF IsIconic(hWndHim THEN
            ShowWindow(hWndHim, %SW_RESTORE)
            ShowWindow(hWndHim, %SW_SHOW)
         END IF