Пел windows on closed

Closing the Window

When the user closes a window, that action triggers a sequence of window messages.

The user can close an application window by clicking the Close button, or by using a keyboard shortcut such as ALT+F4. Any of these actions causes the window to receive a WM_CLOSE message. The WM_CLOSE message gives you an opportunity to prompt the user before closing the window. If you really do want to close the window, call the DestroyWindow function. Otherwise, simply return zero from the WM_CLOSE message, and the operating system will ignore the message and not destroy the window.

Here is an example of how a program might handle WM_CLOSE.

In this example, the MessageBox function shows a modal dialog that contains OK and Cancel buttons. If the user clicks OK, the program calls DestroyWindow. Otherwise, if the user clicks Cancel, the call to DestroyWindow is skipped, and the window remains open. In either case, return zero to indicate that you handled the message.

If you want to close the window without prompting the user, you could simply call DestroyWindow without the call to MessageBox. However, there is a shortcut in this case. Recall that DefWindowProc executes the default action for any window message. In the case of WM_CLOSE, DefWindowProc automatically calls DestroyWindow. That means if you ignore the WM_CLOSE message in your switch statement, the window is destroyed by default.

When a window is about to be destroyed, it receives a WM_DESTROY message. This message is sent after the window is removed from the screen, but before the destruction occurs (in particular, before any child windows are destroyed).

In your main application window, you will typically respond to WM_DESTROY by calling PostQuitMessage.

We saw in the Window Messages section that PostQuitMessage puts a WM_QUIT message on the message queue, causing the message loop to end.

Here is a flow chart showing the typical way to process WM_CLOSE and WM_DESTROY messages:

Window. Close Метод

Определение

Вручную закрывает окно Window. Manually closes a Window.

Примеры

В следующем примере показан файл | меню выхода , обрабатываемого для явного вызова Close . The following example shows a File | Exit menu being handled to explicitly call Close.

Комментарии

WindowМожно закрыть с помощью одного из нескольких хорошо известных, предоставляемых системой механизмов, расположенных в его заголовке, в том числе: A Window can be closed using one of several, well-known, system-provided mechanisms located in its title bar, including:

Системное меню | Закрыть. System menu | Close.

Кнопка » Закрыть «. Close button.

WindowТакже можно закрыть с помощью одного из нескольких хорошо известных механизмов в клиентской области, предоставляемых разработчиками, включая: A Window can also be closed using one of several well-known mechanisms within the client area that are provided by developers, including:

Файл | выйти из главного окна. File | Exit on a main window.

Файл | Закрыть или кнопку Закрыть в дочернем окне. File | Close or a Close button on a child window.

Кнопки ОК и Отмена в диалоговом окне также предоставляются разработчиками, хотя, скорее всего, будет установлено DialogResult , которое автоматически закроет окно, открытое при вызове ShowDialog . OK and Cancel buttons on a dialog box are also developer-provided, although will likely set DialogResult, which automatically closes a window that was opened by calling ShowDialog.

Эти механизмы потребовали явного вызова Close для закрытия окна. These mechanisms require you to explicitly call Close to close a window.

Если окно, открытое путем вызова ShowDialog , и со Button IsCancel свойством, для которого задано значение true, автоматически закроется при нажатии кнопки, или если нажать клавишу ESC. If a window, opened by calling ShowDialog, and with a Button with its IsCancel property set to true, will automatically close when the button is either clicked, or ESC is pressed. Если окно было открыто с помощью Show , Close необходимо явно вызвать метод, например из Click обработчика событий для Button . If the window was opened using Show, however, Close must be explicitly called, such as from Click event handler for the Button.

Читайте также:  Пакеты rpm для линукс

Закрытие окна приводит к Closing возникновению события. Closing a window causes the Closing event to be raised. Если Closing событие не отменено, происходит следующее: If the Closing event isn’t canceled, the following occurs:

WindowУдаляется из Application.Windows (если Application объект существует). The Window is removed from Application.Windows (if an Application object exists).

WindowУдаляется из владельца, Window если отношение владельца и владелец было установлено до того, как Window было отображено и после открытия владельца Window . The Window is removed from the owner Window if the owner/owned relationship was established before the owned Window was shown and after the owner Window was opened.

Возникает событие Closed. The Closed event is raised.

Неуправляемые ресурсы, созданные объектом, Window уничтожаются. Unmanaged resources created by the Window are disposed.

Если ShowDialog был вызван для отображения Window , ShowDialog возвращает. If ShowDialog was called to show the Window, ShowDialog returns.

При закрытии Window вызывается закрытие всех окон, которыми он владеет. Closing a Window causes any windows that it owns to be closed. Кроме того, закрытие Window может привести к прекращению работы приложения в зависимости от того, как Application.ShutdownMode это свойство задано. Furthermore, closing a Window may cause an application to stop running depending on how the Application.ShutdownMode property is set.

Этот метод не может быть вызван, если окно размещается в браузере. This method cannot be called when a window is hosted in a browser.

Win 10 — computer won’t lock or sleep when lid is closed

upgraded to win 10 and now my laptop won’t lock or sleep when I close the lid. Computer stays on and kills my battery at night. I have gone into the control panel and adv settings in power to make sure that on lid close it is on sleep. Verified that yes it is. On win 8 my computer would lock when I close the lid but now it doesn’t do that either. Getting frustrated already with Win 10.

Replies (29) 

* Please try a lower page number.

* Please enter only numbers.

* Please try a lower page number.

* Please enter only numbers.

Thank you for posting on Microsoft Communities.

Please follow the methods mentioned below:

Method 1 : Follow the steps:

Press Windows Key + X.

Select on Control Panel.

Click on Power Options. On the left, click on «Choose what closing the lid does». Click on the drop down menu for «When I close the lid» and choose «Sleep» or «Hibernate.

Method 2 : I suggest you to run in-built Power troubleshooter and check. Follow the steps:

  1. Press Windows Key + X.
  2. Click on Control Panel.
  3. Select Troubleshooting on the left pane, click on View All.
  4. Click on Power to run the troubleshooter.

Method 3 : If the above method doesn’t help, I would suggest you to reset and restore all of the default Power Plans back with their default settings. Follow the steps.

  1. Press Windows Key + X.
  2. Select Command Prompt (Admin).
  3. At the command prompt, type powercfg -restoredefaultschemes, and then press ENTER.
  4. At the command prompt, type exit to exit the Command Prompt window.
  5. Restart the computer and check with the issue.

Let us know if the issue is resolved or if you require further assistance.

Windows 10 external monitor with lid closed but only when connected

I am using my Win 10 laptop either as a standalone laptop or in a desktop setup with an external monitor attached and my lid closed. What I want is that in my desktop environment, the computer doen’t go to sleep when I close the lid (I know how to do that in the energy settings) and when I use my laptop without an external monitor attached, then it should go to sleep when I close the lid.

Читайте также:  Как linux планки памяти

How can I condition the energy behaviour on whether an external display is attached?

Thx for the help

Replies (18) 

* Please try a lower page number.

* Please enter only numbers.

* Please try a lower page number.

* Please enter only numbers.

I suggest you to try the steps below and check if it helps.

Run the Power Troubleshooter.

Power troubleshooter will automatically fix some common issues with Power Plans. Run the Power troubleshooter to adjust your computer’s power settings. The Power troubleshooter checks things like your computer’s timeout settings, which determine how long the computer waits before turning off the monitor display or entering sleep mode. Adjusting these settings can help you conserve power and extend your computer’s battery life.

Press Windows key + W and type Troubleshooting.

Select Troubleshooting and click on System and Security.

Click on Power and follow the onscreen steps.

Also, t ry to put the system in Clean Boot. This helps eliminate software conflicts that occur when you install a program or an update or when you run a program in Windows. It starts Windows by using a minimal set of drivers and startup programs.
How to perform a Clean Boot in Windows: http://support.microsoft.com/kb/929135

Note: After troubleshooting, refer to this section «How to reset the computer to start normally after clean boot troubleshooting» in the above link.

Hope this helps in resolving the issue. If the issue persists, do get back to us. We will be happy to assist you.

14 people found this reply helpful

Was this reply helpful?

Sorry this didn’t help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

I suggest you to try the steps below and check if it helps.

Run the Power Troubleshooter.

Power troubleshooter will automatically fix some common issues with Power Plans. Run the Power troubleshooter to adjust your computer’s power settings. The Power troubleshooter checks things like your computer’s timeout settings, which determine how long the computer waits before turning off the monitor display or entering sleep mode. Adjusting these settings can help you conserve power and extend your computer’s battery life.

Press Windows key + W and type Troubleshooting.

Select Troubleshooting and click on System and Security.

Click on Power and follow the onscreen steps.

Also, t ry to put the system in Clean Boot. This helps eliminate software conflicts that occur when you install a program or an update or when you run a program in Windows. It starts Windows by using a minimal set of drivers and startup programs.
How to perform a Clean Boot in Windows: http://support.microsoft.com/kb/929135

Note: After troubleshooting, refer to this section «How to reset the computer to start normally after clean boot troubleshooting» in the above link.

Hope this helps in resolving the issue. If the issue persists, do get back to us. We will be happy to assist you.

Sometimes I wonder if you guys even read the questions you are asked.

window.close и self.close не закрывают окно в Chrome

Проблема в том, что когда я вызываю window.close() или self.close() он не закрывает окно. Теперь кажется, что в Chrome невозможно закрыть с помощью скрипта любое окно, которое не было создано скриптом. Это явно неверно, но независимо от того, что он все еще должен это делать, даже если для подтверждения требуется всплывающее предупреждение. Это не происходит.

Так есть ли у кого-нибудь реальный, функциональный и проверенный метод закрытия окна с использованием чего-то подобного javascript:window.close() или javascript:self.close() действительно выполняющий то, что ожидается, и то, что происходит просто отлично в каждом браузере, НЕ основанном на Chrome? Любые предложения будут с благодарностью, и я ищу Javascript для конкретного решения, ничего JQuery или сторонней реализации.

Обновление: хотя большая часть из того, что было предложено, имеет серьезные ограничения и проблемы с удобством использования, последнее предложение (специфичное для TamperMonkey), используемое // @grant window.close в заголовке скрипта, часто помогает, даже на тех вкладках, которые обычно не могут обработать метод close. Хотя это не совсем идеально и не обобщается на каждый случай, в моем случае это хорошее решение.

Читайте также:  Ntlite windows 10 что удалить

Обычный javascript не может закрывать окна волей-неволей. Это функция безопасности, представленная некоторое время назад, для предотвращения различных злонамеренных эксплойтов и неприятностей.

close() Метод на Window объекты должны, если все следующие условия, близко контекст просмотра :

  • Соответствующий контекст просмотра A является закрываемым сценарием .
  • Контекстное просмотр действующего сценария знаком с контекстным просмотра A .
  • Просмотра контекста сценария действующего разрешено перемещаться контекстным просмотр A .

Контекст просмотра может быть закрыт сценарием, если он является вспомогательным контекстом просмотра, созданным сценарием (в отличие от действий пользователя), или если это контекст просмотра, история сеанса которого содержит только один Документ.

Это означает, что за одним небольшим исключением нельзя разрешать JavaScript закрывать окно, которое не было открыто этим же JavaScript.

Chrome допускает это исключение, которое не распространяется на пользовательские скрипты, а Firefox — нет. Реализация Firefox гласит :

Этот метод разрешается вызывать только для тех окон, которые были открыты скриптом с использованием window.open метода.

Если вы пытаетесь использовать window.close с Greasemonkey / Tampermonkey / userscript вы получите:
Firefox: Сообщение об ошибке « Scripts may not close windows that were not opened by script. »
Chrome: просто молча терпит неудачу.

Долгосрочное решение:

Лучший способ справиться с этим — создать вместо него расширение Chrome и / или дополнение для Firefox. Они могут надежно закрыть текущее окно.

Тем не менее, поскольку риски безопасности, связанные с этим window.close , намного меньше для сценария Greasemonkey / Tampermonkey; Greasemonkey и Tampermonkey могли бы разумно предоставить эту функциональность в их API (по сути, упаковывая работу расширения для вас).
Рассмотрите возможность запроса функции.

Хакерские обходные пути:

В настоящее время Chrome был уязвим для эксплойта «самостоятельного перенаправления». Так что код, подобный этому, работал в целом:

Это ошибочное поведение, IMO, и сейчас (по состоянию на апрель 2015 года) в основном заблокировано. Он все равно будет работать из введенного кода, только если вкладка была недавно открыта и не имеет страниц в истории просмотра. Так что это полезно только в очень небольших обстоятельствах.

Тем не менее, вариант все еще работает на Chrome (v43 и v44) плюс Tampermonkey (v3.11 или более поздняя версия) . Используйте явное @grant и простое window.close() . НАПРИМЕР:

Спасибо zanetu за обновление. Обратите внимание, что это не будет работать, если открыта только одна вкладка. Закрывает только дополнительные вкладки.

Fire Fox защищен от этой атаки. Таким образом, единственный способ javascript — нанести вред настройкам безопасности, по одному браузеру за раз.

Вы можете открыть about:config и установить
allow_scripts_to_close_windows на true .

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

Там в настоящее время нет эквивалентной настройки для Chrome.

Chrome Исправлены проблемы безопасности в версии 36.0.1985.125

Chrome 36.0.1985.125 СРЕДА, 16 ИЮЛЯ 2014 выпуске

По моим наблюдениям, это обновление исправило проблему с использованием window.close() для закрытия всплывающего окна. Вы увидите это в консоли, когда произойдет сбой: «Сценарии могут закрывать только те окна, которые были открыты им». Это означает, что хакерские обходные пути (ответ Брока Адамса) могут не работать в последней версии.

Таким образом, в предыдущих выпущенных сборках Chrome приведенный ниже блок кода мог работать, но не с этим обновлением.

Для этого обновления вы должны соответствующим образом обновить свой код, чтобы закрыть всплывающее окно. Одним из решений является захват идентификатора всплывающего окна и использование

способ удалить это. API-интерфейс расширений Chrome можно найти по адресу chrome.windows .

Собственно мое хромовое расширение MarkView столкнулось с этой проблемой, и мне пришлось обновить свой код, чтобы он работал для этого обновления Chrome. Кстати, MarkView — это инструмент для чтения и записи Awesome Markdown Files, он предоставляет такие функции, как структура содержимого, сортируемые таблицы и подсветка синтаксиса блока кода с номером строки.

Я также создал этот пост , любые комментарии приветствуются.

Оцените статью