Skip to content

Instantly share code, notes, and snippets.

@CaptainJH
Created August 26, 2014 06:25
Show Gist options
  • Select an option

  • Save CaptainJH/f8d74747cf352f010df6 to your computer and use it in GitHub Desktop.

Select an option

Save CaptainJH/f8d74747cf352f010df6 to your computer and use it in GitHub Desktop.

Revisions

  1. CaptainJH created this gist Aug 26, 2014.
    55 changes: 55 additions & 0 deletions bringToFront.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    void SetForegroundWindowInternal(HWND hWnd)
    {
    if (!::IsWindow(hWnd)) return;

    BYTE keyState[256] = { 0 };
    //to unlock SetForegroundWindow we need to imitate Alt pressing
    if (::GetKeyboardState((LPBYTE)&keyState))
    {
    if (!(keyState[VK_MENU] & 0x80))
    {
    ::keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
    }
    }

    ::SetForegroundWindow(hWnd);

    if (::GetKeyboardState((LPBYTE)&keyState))
    {
    if (!(keyState[VK_MENU] & 0x80))
    {
    ::keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
    }
    }
    }

    //void SetForegroundWindowInternal(HWND hWnd)
    //{
    // if (!::IsWindow(hWnd))
    // return;
    //
    // //relation time of SetForegroundWindow lock
    // DWORD lockTimeOut = 0;
    // HWND hCurrWnd = ::GetForegroundWindow();
    // DWORD dwThisTID = ::GetCurrentThreadId(),
    // dwCurrTID = ::GetWindowThreadProcessId(hCurrWnd, 0);
    //
    // //we need to bypass some limitations from Microsoft :)
    // if (dwThisTID != dwCurrTID)
    // {
    // ::AttachThreadInput(dwThisTID, dwCurrTID, TRUE);
    //
    // ::SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &lockTimeOut, 0);
    // ::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
    //
    // ::AllowSetForegroundWindow(ASFW_ANY);
    // }
    //
    // ::SetForegroundWindow(hWnd);
    //
    // if (dwThisTID != dwCurrTID)
    // {
    // ::SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)lockTimeOut, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
    // ::AttachThreadInput(dwThisTID, dwCurrTID, FALSE);
    // }
    //}