Close current window windows

Quickly Close Open Windows Using Shortcut Keys

How to type your way out of a mess with Windows keyboard shortcuts

One of the advantages of Microsoft Windows PCs is that you can have many different programs and windows open at the same time. This advantage becomes a disadvantage, however, when you have to close dozens of open windows. Fortunately, you can carry out repetitive actions like closing windows with keyboard shortcuts.

Instructions in this article apply to Windows 10, Windows 8, Windows 7, Windows Vista, and Windows XP.

How to Close Windows With Alt + Spacebar + C

One option for closing windows with keyboard shortcuts is as follows:

Open the window that you would like to close using your mouse.

Press and hold down the Alt key, then press the Spacebar to reveal the right-click context menu at the top of the program window you’re trying to close.

Release both keys and press the letter C. This will cause the window to close.

If you can execute this sequence using one hand while the other hand controls the mouse, you’ll be able to close roughly a dozen windows in about as many seconds.

How to Close Windows With Fn + Alt + F4

Another option is to select the window you want to close and then press Fn+Alt+F4. You’ll probably need two hands for this one.

Although the shortcut is officially listed as Alt+F4, you must hold down the Function (Fn) key for it to work.

How to Close Tabs With CTRL + W

The Ctrl+W shortcut only closes the current file you’re working on, but it leaves the program open. This feature can be handy if you want to leave the desktop program open but get rid of all the files you’re working on in quick succession.

Ctrl+W works in most browsers too, so you can close the current tab you’re looking at without taking your hands off the keyboard. If you use Ctrl+W when only one browser tab is open, then the program window will close.

How to Select Open Windows With Alt + Tab

It’s possible to select an open window without using the mouse. Press Alt+Tab to cycle through your open windows. Use this shortcut in conjunction with the other shortcuts to close all open windows without taking your hands off the keyboard.

How to See Your Desktop With Windows Key + D

Sometimes you don’t actually want to close all those windows; what you really want to do is just look at your desktop. To quickly access your desktop, press the Windows Key+D. Use the same shortcut to bring back all your windows.

If you are running Windows 7 or later, there are multiple ways to access your Windows desktop.

How to Close a Group of Windows With the Mouse

When you have numerous files open in the same program, like a bunch of emails in Outlook, Word files, or several spreadsheets in Excel, you can close all of them at once using the mouse. Right-click the program in the Windows taskbar and select Close all windows (or Close Group in older versions of Windows).

Читайте также:  Kali linux для процессоров intel

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.

Читайте также:  Windows bind to domain

Если окно, открытое путем вызова 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.

Закрытие окна приводит к 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.

How to close current tab in a browser window?

I want to create a link on a webpage that would close the currently active tab in a browser without closing other tabs in the browser.
When the user clicks the close link, an alert message should appear asking the user to confirm with two buttons, «YES» and «NO». If the user clicks «YES», close that page and If «NO», do nothing.

How can it be done? Any suggestions?

I might be late here but this is prevented by the browsers for a reason.

Think of yourself trying to close a window again and again and it’s not closing as its doing the «if no» part from your question which is ‘do nothing’.

This will be irritating for sure ! – Muhammad Osama Mar 16 ’19 at 8:54

16 Answers 16

You will need Javascript to do this. Use window.close() :

Note: the current tab is implied. This is equivalent:

or you can specify a different window.

You return false here to prevent the default behavior for the event. Otherwise the browser will attempt to go to that URL (which it obviously isn’t).

Now the options on the window.confirm() dialog box will be OK and Cancel (not Yes and No). If you really want Yes and No you’ll need to create some kind of modal Javascript dialog box.

Note: there is browser-specific differences with the above. If you opened the window with Javascript (via window.open() ) then you are allowed to close the window with javascript. Firefox disallows you from closing other windows. I believe IE will ask the user for confirmation. Other browsers may vary.

Читайте также:  Как изменить дистрибутив linux

This method works in Chrome and IE:

As far as I can tell, it no longer is possible in Chrome or FireFox. It may still be possible in IE (at least pre-Edge).

Sorry for necroposting this, but I recently implemented a locally hosted site that had needed the ability to close the current browser tab and found some interesting workarounds that are not well documented anywhere I could find, so took it on myself to do so.

Note: These workarounds were done with a locally hosted site in mind, and (with the exception of Edge) require the browser to be specifically configured, so would not be ideal for publicly hosted sites.

Context: In the past, the jQuery script window.close() was able to close the current tab without a problem on most browsers. However, modern browsers no longer support this script, potentially for security reasons.

Google Chrome:

Chrome does not allow the window.close() script to be to be run and nothing happens if you try to use it. By using the Chrome plugin TamperMonkey however we can use the window.close() method if you include the // @grant window.close in the UserScript header of TamperMonkey.

For example, my script (which is triggered when a button with is clicked and if ‘yes’ is pressed on the browser popup) looks like:

Note: This solution can only close the tab if it is NOT the last tab open however. So effectively, it cannot close the tab if it would cause window to closes by being the last tab open.

Firefox:

Firefox has an advanced setting that you can enable to allow scripts to close windows, effectively enabling the window.close() method. To enable this setting go to about:config then search and find the dom.allow_scripts_to_close_windows preference and switch it from false to true.

This allows you to use the window.close() method directly in your jQuery file as you would any other script.

For example, this script works perfectly with the preference set to true:

This works much better than the Chrome workaround as it allows the user to close the current tab even if it is the only tab open, and doesn’t require a third party plugin. The one downside however is that it also enables this script to be run by different websites (not just the one you are intending it to use on) so could potentially be a security hazard, although I cant imagine closing the current tab being particularly dangerous.

Disappointingly Edge actually performed the best out of all 3 browsers I tried, and worked with the window.close() method without requiring any configuration. When the window.close() script is run, an additional popup alerts you that the page is trying to close the current tab and asks if you want to continue.

Edit: This was on the old version of Edge not based on chromium. I have not tested it, but imagine it will act similarly to Chrome on chromium based versions

Final Note: The solutions for both Chrome and Firefox are workarounds for something that the browsers intentionally disabled, potentially for security reasons. They also both require the user to configure their browsers up to be compatible before hand, so would likely not be viable for sites intended for public use, but are ideal for locally hosted solutions like mine.

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