共用方式為


SetForegroundWindow 函式 (winuser.h)

將建立指定視窗的執行緒帶到前景並啟用視窗。 鍵盤輸入會導向至視窗,並會為使用者變更各種視覺提示。 系統會將優先順序指派給建立前景視窗的執行線,比其他執行線程稍高。

語法

BOOL SetForegroundWindow(
  [in] HWND hWnd
);

參數

[in] hWnd

類型:HWND

應該啟用並移至前景的視窗控制碼。

返回值

類型: 布爾值

如果視窗已帶到前景,則傳回值為非零。

如果視窗未帶到前景,則傳回值為零。

備註

系統會限制哪些進程可以設定前景視窗。 只有在下列情況下,進程才能呼叫 SetForegroundWindow 來設定前景視窗:

  • 下列所有條件都成立:
    • 呼叫程式屬於傳統型應用程式,而不是針對 Windows 8 或 8.1 設計的 UWP 應用程式或 Windows 市集應用程式。
    • 前景進程尚未停用先前呼叫 LockSetForegroundWindow 函式對 SetForegroundWindow 的呼叫。
    • 沒有作用中的選單。
  • 此外,至少符合下列其中一個條件:
    • 前景鎖定逾時已過期 (請參閱 SystemParametersInfo) 中的SPI_GETFOREGROUNDLOCKTIMEOUT
    • 呼叫進程是前景進程。
    • 呼叫程序是由前景程序啟動的。
    • 目前沒有前景視窗,因此沒有前景進程。
    • 呼叫處理程序收到最後一個輸入事件。
    • 正在偵錯前景進程或呼叫進程。

即使進程符合這些條件,也有可能拒絕設定前景視窗的權利。

當使用者使用另一個視窗時,應用程式無法強制視窗進入前景。 相反地,Windows 會閃爍視窗的工作列按鈕來通知使用者。

可設定前景視窗的進程可以呼叫 AllowSetForegroundWindow 函式,讓另一個進程來設定前景視窗。 dwProcessId 參數指定至 AllowSetForegroundWindow 的進程會失去設定前景視窗的能力,除非輸入指向該進程,除非輸入指向該進程,或下次進程呼叫 AllowSetForegroundWindow 時,除非指定的進程與上次呼叫 AllowSetForegroundWindow 相同的進程。

前景進程可以呼叫 LockSetForegroundWindow 函式來停用對 SetForegroundWindow 的呼叫。

Example

下列程式碼範例示範如何使用 SetForegroundWindow

// If the window is invisible we will show it and make it topmost without the
// foreground focus. If the window is visible it will also be made the
// topmost window without the foreground focus. If wParam is TRUE then
// for both cases the window will be forced into the foreground focus
if (uMsg == m_ShowStageMessage) {
    BOOL bVisible = IsWindowVisible(hwnd);
    SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
                    SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW |
                    (bVisible ? SWP_NOACTIVATE : 0));
    // Should we bring the window to the foreground
    if (wParam == TRUE) {
        SetForegroundWindow(hwnd);
    }
    return (LRESULT) 1;
}

需求

Requirement 價值觀
最低支援的用戶端 Windows 2000 Professional [僅限傳統型應用程式]
支援的最低伺服器 Windows 2000 Server [僅限傳統型應用程式]
目標平臺 窗戶
Header winuser.h (包括 Windows.h)
Library 用戶32.lib
DLL User32.dll
API 集 ext-ms-win-ntuser-window-l1-1-0 (Windows 8 中引進)

另請參閱

允許設定前景視窗

概念

閃光視窗Ex

GetForeground視窗

鎖定設定前景視窗

參考

設定主動視窗

Windows 作業系統