Windows set foreground window

Windows set foreground window

Функция SetForegroundWindow переводит поток, который создал заданное окно в приоритетный режим и активизирует окно. Ввод с клавиатуры направляется в окно, а различные визуальные ориентиры для пользователя изменяются. Система назначает немного более высокий приоритет потоку, который создал приоритетное окно, чем она делает это по отношению к другим потокам.

HWND hWnd // дескриптор окна, которое
// переводится в приоритетный режим

[in] Дескриптор окна, которое должно быть активизировано и переведено в приоритетный режим.

Если окно переведено в приоритетный режим, возвращаемое значение — не нуль.

Если окно не переведено в приоритетный режим, возвращаемое значение — ноль.

Приоритетное окно является окном наверху Z-последовательности . Это — окно, с которым пользователь работает. В среде вытесняющей многозадачности, Вы должны вообще дать возможность управления пользователю, окно которого является приоритетным окном.

Windows 98/Me: система ограничивает число процессов, которые могут устанавливать приоритетное окно. Процесс может установить приоритетное окно, только в том случае, если имеет место одно из ниже перечисленных условий:

  • Процесс — приоритетный процесс.
  • Процесс был запущен приоритетным процессом.
  • Процесс получил последнее событие ввода.
  • Не имеется никакого приоритетного процесса.
  • Приоритетный процесс отлаживается.
  • Активный режим не блокирован (см. функцию LockSetForegroundWindow ).
  • Блокировка по времени приоритетного режима истекла (см. флажок SPI_GETFOREGROUNDLOCKTIMEOUT в функции SystemParametersInfo ).
  • Windows 2000/XP: Нет активного меню.

Этот метод позволяет функции SetForegroundWindow в Windows 98/Windows Me и Windows 2000 /Windows XP, вести себя точно так же, как и в Windows 95 и Windows NT 4.0, соответственно, во всех прикладных программах. Приложение установки программы должно предупредить пользователя, что это делается таким образом, чтобы пользователь не удивлялся изменению режима работы. В окнах Windows 2000 и Windows XP, вызов завершается ошибкой, если вызывающий поток не может изменить приоритетное окно, так что функция должна вызываться из установки или вставки («заплатки») программы. Для получения дополнительной информации, см. статью Приоритетные и фоновые окна .

Процесс, который может устанавливать приоритетное окно, может дать возможность другому процессу установить приоритетное окно путем вызова функции AllowSetForegroundWindow . Процесс, определенный при помощи параметра dwProcessId теряет способность устанавливать приоритетное окно в следующий раз, когда пользователь производит ввод данных до тех пор, пока ввод данных не будет направлен в этот процесс, или в следующий раз, когда процесс вызывает функцию AllowSetForegroundWindow , если этот процесс не определен.

Приоритетный процесс может отключать вызовы функции SetForegroundWindow путем вызова функции LockSetForegroundWindow .

SetForegroundWindow function (winuser.h)

Brings the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.

Syntax

Parameters

A handle to the window that should be activated and brought to the foreground.

Return value

If the window was brought to the foreground, the return value is nonzero.

If the window was not brought to the foreground, the return value is zero.

Remarks

The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The process is being debugged.
  • The foreground process is not a Modern Application or the Start Screen.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.

An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.

A process that can set the foreground window can enable another process to set the foreground window by calling the AllowSetForegroundWindow function. The process specified by dwProcessId loses the ability to set the foreground window the next time the user generates input, unless the input is directed at that process, or the next time a process calls AllowSetForegroundWindow, unless that process is specified.

The foreground process can disable calls to SetForegroundWindow by calling the LockSetForegroundWindow function.

Example

The following code example demonstrates the use of SetForegroundWindow

Развернуть форму из трея через SetForegroundWindow

В общем при запуске программы, она находит другой процесс Z по имени и вызывает его командой SetForegroundWindow(Z.MainWindowHandle). Если окно свернуто или находиться на заднем плане, оно естественно станет активным. Проблема появляется, если окно находиться трее. Оно становиться активным при обращении, но остается в хайде.
Вызывает ли SetForegroundWindow какое-нибудь событие? И если да, то какое? Пробовал и Enter и Click, всё бестолку=( Или может быть есть другой способ как мне развернуть такое окно?

Как развернуть форму из трея?
Всем привет:) Как программно развернуть программу из трея?

Развернуть програму из трея
Короче свернул программу в трей при помощи Shell_NotifyIcon, немогу развернуть обратно, то что я.

Развернуть приложение из трея
Добрый день, тема не новая, но ответа не нашел. Как через WinApi можно развернуть приложение из.

Развернуть программу из трея
Таким образом сворачивается программа в трей- procedure TForm1.Button1Click(Sender: TObject);.

Решение

Увы, не помогло. Вот код. Пытался и больше команд добавить, но всё так же=(

Тематические курсы и обучение профессиям онлайн
Профессия‌ С#-разработчик‌ (Skillbox)
Архитектор ПО (Skillbox)
Профессия Тестировщик (Skillbox)

а из трея не работает
вся проблема когда я прячу форму в трей я на панели задач ее прячу тоже через Hide();

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Не получается развернуть приложение из трея
Доброго времени суток форумчане. Подскажите по каким причинам может не работать команда.

Развернуть копию программы из трея
Нужно чтобы 2ая копию программы разворачивала 1уй копию программы. Много читал по форумам но так и.

Развернуть из трея по щелчку — не хочет нивкакую
Сворачиваю в трей по нажатию на кнопку: private void Tray_bt_Click(object sender, EventArgs e) .

Зависают torrent-программы, развернуть из трея не удается
Сначала мюторрент. Через некоторое время работы не отвечает. Развернуть из трея тоже не.

AllowSetForegroundWindow function (winuser.h)

Enables the specified process to set the foreground window using the SetForegroundWindow function. The calling process must already be able to set the foreground window. For more information, see Remarks later in this topic.

Syntax

Parameters

The identifier of the process that will be enabled to set the foreground window. If this parameter is ASFW_ANY, all processes will be enabled to set the foreground window.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The function will fail if the calling process cannot set the foreground window. To get extended error information, call GetLastError.

Remarks

The system restricts which processes can set the foreground window. A process can set the foreground window only if one of the following conditions is true:

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.

A process that can set the foreground window can enable another process to set the foreground window by calling AllowSetForegroundWindow. The process specified by dwProcessId loses the ability to set the foreground window the next time the user generates input, unless the input is directed at that process, or the next time a process calls AllowSetForegroundWindow, unless that process is specified.

Win32 SetForegroundWindow unreliable

I have a rather complex series of applications which depend on the ability to switch applications in the foreground.

My problem is, every 5 or 6 times of switching the applications in the foreground, it simply fails to bring the application forward. GetLastError does not report any issues. Often times I see the correct application flash in the foreground for a moment then the previous application is visible.

I have a Manager application which I have source for, it spawns and controls about 4 applications which I do not have source for. one of the applications it spawns/controls is also a manager which spawns/controls about 5 applications.

This is a sort of kiosk design so the user wont even have a keyboard or mouse, just a touch screen.

I have tried every combination of the Win32 calls to control them I am just out of ideas.

My first attempt was:

My second attempt was:

my third attempt: DWORD dwThreadID = GetWindowThreadProcessId(hApp, NULL); AttachThreadInput( dwThreadID, GetCurrentThreadId(), true);

my forth attempt:

I feel like I am missing an important gotcha when it comes to window switching. I know that only the foreground process can switch windows around but as my main Manager program is spawning and starting all the other processes which I need to control, I feel like it should be capable of moving these windows around. Any suggestions or advice is appreciated.

Читайте также:  What are semaphores linux
Оцените статью